Trapos#
Introducción#
Los subprocesos permiten que un robot ejecute múltiples tareas simultáneamente dentro del mismo programa. Facilitan la multitarea, permitiendo que el robot realice acciones independientes simultáneamente.
Note: You must first define a function to use it with a thread.
Constructor – Crea e inicia nuevos hilos.
Thread – Starts a new thread that runs the specified function in parallel with the main program.
Acción – Controlar hilos en ejecución.
stop – Stops a thread manually, useful for halting background behavior.
Constructor#
Thread#
Thread
crea e inicia un hilo. Al crear un hilo, puedes nombrarlo para gestionarlo individualmente en tu proyecto.
Uso:
my_thread = Thread(my_function)
Parámetros |
Descripción |
---|---|
|
Opcional. Un nombre para el nuevo hilo. |
|
El nombre de una función definida previamente. |
Nota: Una función siempre debe definirse antes de ser llamada.
# 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
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
.
Uso:
my_thread.stop()
Parámetros |
Descripción |
---|---|
|
Un objeto de hilo iniciado previamente. Este es el nombre asignado al crear el hilo con |
"""
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()