Hilos#

Introducción#

Los subprocesos permiten que un robot ejecute múltiples tareas simultáneamente dentro del mismo programa. Permiten la multitarea, dejando que el robot realice acciones independientes al mismo tiempo.

Nota: Debes definir primero una función para usarla con un hilo.

Constructor: crea e inicia nuevos subprocesos.

  • Thread – Inicia un nuevo hilo que ejecuta la función especificada en paralelo con el programa principal.

Acción: controle los subprocesos en ejecución.

  • stop – Detiene un hilo manualmente, útil para detener el comportamiento de fondo.

Constructor#

Thread#

Thread crea e inicia un subproceso. Cuando creas un hilo, puedes nombrarlo para detenerlo cuando ya no sea necesario.

Uso:

my_thread = Thread(my_function)

Parámetros

Descripción

my_thread

Opcional. Un nombre para el nuevo hilo.

my_function

El nombre de una función previamente definida.

Nota: Una función debe definirse siempre antes de que se llame.

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

Acción#

stop#

stop detiene un subproceso manualmente, lo cual es útil cuando ya no se necesita una tarea o cuando un programa necesita restablecer los subprocesos. Una vez que se detiene un hilo, no se puede reiniciar. Para ejecutarlo de nuevo, debe crear un nuevo subproceso usando Subproceso.

Uso:

my_thread.stop()

Parámetros

Descripción

my_thread

Un objeto de subproceso iniciado previamente. Este es el nombre asignado cuando se creó el subproceso utilizando el 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()