執行緒#
介紹#
執行緒允許機器人在同一程式中同時執行多個任務。它們實現了多任務處理,使機器人能夠同時執行獨立的動作。
Note: You must first define a function to use it with a thread.
建構函數-建立並啟動新執行緒。
Thread– 啟動一個新線程,該線程與主程式並行運行指定的函數。
操作 – 控制正在執行的執行緒。
stop– 手動停止線程,可用於停止後台行為。
建構函數#
Thread#
Thread 創建並啟動一個線程。建立線程時,您可以為其命名,以便在不再需要時將其停止。
用法:
my_thread = Thread(my_function)
參數 |
描述 |
|---|---|
|
(可選)新帖子的名稱。 |
|
先前定義的函數的名稱。 |
Note: A function must always be defined before it is called.
# Drive forward while blinking screen
def blink_screen():
while True:
brain.screen.clear_screen(Color.RED)
wait(0.5, SECONDS)
brain.screen.clear_screen()
wait(0.5, SECONDS)
blink_screen_thread = Thread(blink_screen)
drivetrain.drive(FORWARD)
# Run multiple threads simultaneously
# Turn right, blink screen at once
def blink_screen():
while True:
brain.screen.clear_screen(Color.RED)
wait(0.5, SECONDS)
brain.screen.clear_screen()
wait(0.5, SECONDS)
def turning():
drivetrain.turn(RIGHT)
blink_screen_thread = Thread(blink_screen)
turning_thread = Thread(turning)
行動#
stop#
stop 手動停止線程,這在不再需要某個任務或程式需要重置線程時非常有用。線程一旦停止,就無法重新啟動。要再次運行它,必須使用 Thread 建立一個新執行緒。
用法:
my_thread.stop()
參數 |
描述 |
|---|---|
|
先前啟動的線程物件。這是使用 |
"""
Run multiple threads simultaneously
Turn right, play a sound and display heading at once
Stop playing sounds after 2 seconds
"""
def lights():
while True:
optical_sensor.set_light(LEDStateType.ON)
wait(0.5, SECONDS)
optical_sensor.set_light(LEDStateType.OFF)
wait(0.5, SECONDS)
def display_heading():
while True:
brain.screen.clear_row()
brain.screen.set_cursor(1, 1)
brain.screen.print("Heading: {}".format(drivetrain.heading(DEGREES)))
wait(50, MSEC)
lights_thread = Thread(lights)
display_heading_thread = Thread(display_heading)
drivetrain.turn(RIGHT)
wait(2, SECONDS)
lights_thread.stop()