Fios#

Introdução#

Os threads permitem que um robô execute várias tarefas em simultâneo dentro do mesmo programa. Possibilitam a multitarefa, permitindo que o robô execute ações independentes ao mesmo tempo.

Nota: Deve primeiro definir uma função para a utilizar com um thread.

Construtor – Cria e inicia novos threads.

  • Thread – Inicia uma nova thread que executa a função especificada em paralelo com o programa principal.

Ação – Controlar threads em execução.

  • stop – Interrompe um thread manualmente, útil para interromper o comportamento em segundo plano.

Construtor#

Thread#

Thread cria e inicia uma thread. Ao criar uma thread, pode nomeá-la para a interromper quando já não for necessária.

Utilização:

my_thread = Thread(my_function)

Parâmetros

Descrição

my_thread

Opcional. Um nome para o novo tópico.

my_function

O nome de uma função previamente definida.

Nota: Uma função deve ser sempre definida antes de ser chamada.

# 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)

Ação#

stop#

stop pára um thread manualmente, o que é útil quando uma tarefa já não é necessária ou quando um programa necessita de reiniciar threads. Uma vez que uma thread é interrompida, não pode ser reiniciada. Para a executar novamente, deve criar uma nova thread utilizando Thread.

Utilização:

my_thread.stop()

Parâmetros

Descrição

my_thread

Um objeto de thread previamente iniciado. Este é o nome atribuído quando o thread foi criado utilizando 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()