Fils#
Introduction#
Les threads permettent à un robot d’exécuter plusieurs tâches simultanément au sein d’un même programme. Ils rendent possible le multitâche, permettant au robot d’effectuer des actions indépendantes en même temps.
Remarque : Vous devez d’abord définir une fonction pour l’utiliser avec un thread.
Constructeur – Créer et démarrer de nouveaux threads.
Thread– Démarre un nouveau thread qui exécute la fonction spécifiée en parallèle avec le programme principal.
Action – Contrôler les threads en cours d’exécution.
stop– Arrête un thread manuellement, utile pour interrompre le comportement en arrière-plan.
Constructeur#
Thread#
La commande Thread crée et démarre un thread. Lorsque vous créez un thread, vous pouvez le nommer pour l’arrêter lorsqu’il n’est plus nécessaire.
Usage:
my_thread = Thread(my_function)
Paramètres |
Description |
|---|---|
|
Facultatif. Un nom pour la nouvelle discussion. |
|
Le nom d’une fonction précédemment définie. |
Remarque : Une fonction doit toujours être définie avant d’être appelée.
# 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 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()
Paramètres |
Description |
|---|---|
|
Objet thread précédemment démarré. Il s’agit du nom attribué lors de la création du thread à l’aide de |
"""
Run multiple threads simultaneously
Turn right, play a sound and display heading at once
Stop playing sounds after 2 seconds
"""
def lights():
while True:
optical_sensor.set_light(LEDStateType.ON)
wait(0.5, SECONDS)
optical_sensor.set_light(LEDStateType.OFF)
wait(0.5, SECONDS)
def display_heading():
while True:
brain.screen.clear_row()
brain.screen.set_cursor(1, 1)
brain.screen.print("Heading: {}".format(drivetrain.heading(DEGREES)))
wait(50, MSEC)
lights_thread = Thread(lights)
display_heading_thread = Thread(display_heading)
drivetrain.turn(RIGHT)
wait(2, SECONDS)
lights_thread.stop()