실#
소개#
스레드를 사용하면 로봇이 동일한 프로그램 내에서 여러 작업을 동시에 실행할 수 있습니다. 이를 통해 멀티태스킹이 가능해지며, 로봇이 동시에 독립적인 동작을 수행할 수 있습니다.
Note: You must first define a function to use it with a thread.
생성자 – 새 스레드를 생성하고 시작합니다.
Thread– 지정된 함수를 메인 프로그램과 병렬로 실행하는 새 스레드를 시작합니다.
작업 – 실행 중인 스레드를 제어합니다.
stop– 스레드를 수동으로 중지합니다. 백그라운드 동작을 중지하는 데 유용합니다.
건설자#
Thread#
Thread 스레드를 생성하고 시작합니다. 스레드를 생성할 때 이름을 지정하여 더 이상 필요하지 않을 때 중지할 수 있습니다.
용법:
my_thread = 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()
매개변수 |
설명 |
|---|---|
|
이전에 시작된 스레드 객체입니다. 이는 |
"""
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()