线程#
简介#
线程允许机器人在同一个程序中同时运行多个任务。它们支持多任务处理,让机器人可以同时执行独立的操作。
**注意:**您必须[首先定义一个函数](Functions.md)才能将其与线程一起使用。
构造函数——创建并启动新线程。
[
Thread] (#thread) –启动与主程序并行运行指定函数的新线程。
操作 – 控制正在运行的线程。
[
stop] (#stop) –手动停止线程,用于停止后台行为。
构造函数#
Thread#
Thread 创建并启动线程。创建线程时,您可以将其命名,以便在不再需要时停止。
用法:
my_thread = Thread(my_function)
参数 |
描述 |
|---|---|
|
可选。新线程的名称。 |
|
先前定义的[function] (Functions.md)的名称。 |
注意:函数必须始终在*调用之前定义。
# 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] (#thread)创建一个新线程。
用法:
my_thread.stop()
参数 |
描述 |
|---|---|
|
以前启动的线程对象。这是使用线程创建线程时分配的名 |
"""
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()