Threads#

Introduction#

Threads allow a robot to run multiple tasks simultaneously within the same program. They enable multitasking, letting the robot perform independent actions at the same time.

Note: You must first define a function to use it with a thread.

Constructor – Create and start new threads.

  • Thread – Starts a new thread that runs the specified function in parallel with the main program.

Action – Control running threads.

  • stop – Stops a thread manually, useful for halting background behavior.

Constructor#

Thread#

Thread creates and starts a thread. When you create a thread, you can name it to manage it individually in your project.

Usage:

my_thread = Thread(my_function)

Parameters

Description

my_thread

Optional. A name for the new thread.

my_function

The name of a previously defined 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)

Action#

stop#

stop stops a thread manually, which is useful when a task is no longer needed or when a program needs to reset or reassign threads. Once a thread is stopped, it cannot be restarted. To run it again, you must create a new thread using Thread.

Usage:

my_thread.stop()

Parameters

Description

my_thread

A previously started thread object. This is the name assigned when the thread was created using Thread.

"""
Run multiple threads simultaneously
Turn right, play a sound and display heading at once
Stop playing sounds after 2 seconds
"""
def sound():
    while True:
        brain.play_sound(SoundType.ALARM)
        wait(0.5, SECONDS)

def display_heading():
    while True:
        brain.screen.clear_row()
        brain.screen.set_cursor(1, 1)
        brain.screen.print("Heading: {}".format(brain_inertial.orientation(YAW)))
        wait(50, MSEC)

sound_thread = Thread(sound)     
display_heading_thread = Thread(display_heading)
drivetrain.turn(RIGHT)

wait(2, SECONDS)
sound_thread.stop()