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 arrête manuellement un thread, ce qui est utile lorsqu’une tâche n’est plus nécessaire ou lorsqu’un programme doit réinitialiser les threads. Une fois arrêté, un thread ne peut pas être redémarré. Pour l’exécuter à nouveau, vous devez créer un nouveau thread à l’aide de 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 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()