线程#
介绍#
线程允许机器人在同一程序中同时运行多个任务。它们实现了多任务处理,使机器人能够同时执行独立的动作。
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()