執行緒#

介紹#

執行緒允許機器人在同一程式中同時執行多個任務。它們實現了多任務處理,使機器人能夠同時執行獨立的動作。

注意: 您必须首先定义一个函数才能将其与线程一起使用。

建構函數-建立並啟動新執行緒。

  • Thread – 啟動一個新線程,該線程與主程式並行運行指定的函數。

操作 – 控制正在執行的執行緒。

  • stop – 手動停止線程,可用於停止後台行為。

建構函數#

Thread#

Thread 創建並啟動一個線程。建立線程時,您可以為其命名,以便在不再需要時將其停止。

用法:

my_thread = Thread(my_function)

參數

描述

my_thread

(可選)新帖子的名稱。

my_function

先前定義的函數的名稱。

注意: 函数必须始终在调用之前定义。

# Drive forward while blinking lights
def blink_lights():
    while True:
        robot.led.on(ALL_LEDS, RED)
        wait(0.5, SECONDS)
        robot.led.on(ALL_LEDS, BLUE)
        wait(0.5, SECONDS)
blink_lights_thread = Thread(blink_lights)
robot.move_at(0)

# Run multiple threads simultaneously
# Turn right, blink lights and display heading at once
def blink_lights():
    while True:
        robot.led.on(ALL_LEDS, RED)
        wait(0.5, SECONDS)
        robot.led.on(ALL_LEDS, GREEN)
        wait(0.5, SECONDS)

def display_heading():
    while True:
        robot.screen.clear_row()
        robot.screen.set_cursor(1, 1)
        robot.screen.print(f"Heading: {robot.inertial.get_yaw()}")
        wait(50, MSEC)

blink_lights_thread = Thread(blink_lights)     
display_heading_thread = Thread(display_heading)
robot.turn(RIGHT)

行動#

stop#

stop 手動停止線程,這在不再需要某個任務或程式需要重置線程時非常有用。線程一旦停止,就無法重新啟動。要再次運行它,必須使用 Thread 建立一個新執行緒。

用法:

my_thread.stop()

參數

描述

my_thread

先前啟動的線程物件。這是使用 Thread建立執行緒時指派的名稱。

"""
Run multiple threads simultaneously
Turn right, blink lights and display heading at once
Stop blinking lights after 2 seconds
"""
def blink_lights():
    while True:
        robot.led.on(ALL_LEDS, RED)
        wait(0.5, SECONDS)
        robot.led.off(ALL_LEDS)
        wait(0.5, SECONDS)

def display_heading():
    while True:
        robot.screen.clear_row()
        robot.screen.set_cursor(1, 1)
        robot.screen.print(f"Heading: {robot.inertial.get_yaw()}")
        wait(50, MSEC)

blink_lights_thread = Thread(blink_lights)     
display_heading_thread = Thread(display_heading)
robot.turn(RIGHT)

wait(2, SECONDS)
blink_lights_thread.stop()