Νήματα#

Εισαγωγή#

Τα νήματα επιτρέπουν σε ένα ρομπότ να εκτελεί πολλαπλές εργασίες ταυτόχρονα μέσα στο ίδιο πρόγραμμα. Επιτρέπουν την εκτέλεση πολλαπλών εργασιών, επιτρέποντας στο ρομπότ να εκτελεί ανεξάρτητες ενέργειες ταυτόχρονα.

Σημείωση: Πρέπει πρώτα να ορίσετε μια συνάρτηση για να τη χρησιμοποιήσετε με ένα νήμα.

Κατασκευαστής – Δημιουργήστε και ξεκινήστε νέα νήματα.

  • Thread – Starts a new thread that runs the specified function in parallel with the main program.

Ενέργεια – Έλεγχος των τρεχούμενων νημάτων.

  • stop – Stops a thread manually, useful for halting background behavior.

Κατασκευαστής#

Thread#

Thread creates and starts a thread. When you create a thread, you can name it to stop it when it is no longer needed.

Χρήση:

my_thread = Thread(my_function)

Παράμετροι

Περιγραφή

my_thread

Προαιρετικό. Ένα όνομα για το νέο νήμα.

my_function

Το όνομα μιας προηγουμένως ορισμένης συνάρτησης.

Σημείωση: Μια συνάρτηση πρέπει πάντα να ορίζεται πριν την κλήση της.

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

Δράση#

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.

Χρήση:

my_thread.stop()

Παράμετροι

Περιγραφή

my_thread

A previously started thread object. This is the name assigned when the thread was created using 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()