Multithreading allows different light-weight tasks to efficiently run at the same time. Simply put, a thread is a task, or a separate flow of execution. In other words, it enables multiple tasks to be happening at once. We previously had a light show consisting of five LEDs in red, green, amber and blue. Now, let's try to add another task.
00:00
To illustrate how useful multithreading can be, let's write a new example program with two threads. 
Let’s say we want the on-board LED to join in as part of the light show. First, import the _thread module. 
00:00
Next, create a new function with the following code. It has two parameters, the first is n and the second is delay

00:00
Then assign the on-board LED to the led variable making sure it is set as an output with machine.Pin.OUT. As the on-board LED is on GP25, make sure its first parameter is set to be 25.

00:00
To have the on-board LED blinking a number of times, use a for loop and give it a range (n)

00:00
To turn the led on, simply use the code led.high() and to turn it off, use led.low().

00:00
In between the led.high() and led.low(), add a time.sleep(delay) so there is a pause in between the turning on and off. 

00:00
Finally,  _thread.start_new_thread will start the thread we’ve just defined here! This method requires two parameters. The first parameter is the function that should be called when the thread is ready to run. In this case, it is the on-board LED blink function. The second parameter is a tuple that needs to be passed into the thread. In this example, we have 10 for n  and 0.05 for delay

Then in  while True, replace the redLED.value(1), time.sleep(2) and redLED.value(0) commands with toggle() and time.sleep_ms(150). Do the same for the rest of the LEDs. Upload the code and see what happens!

00:00
Immediately, the on-board LED starts blinking. It continues to blink even when the main light show begins. It then stops after ten times.

00:00
With this code, the on-board LED will blink continuously. 

You’ve now implemented your first multi-threading program! 
00:00
main.py
xxx
Terminal
screen /dev/tty.usbmodem0000000000001 115200
>>> led = Pin(25, Pin.OUT)
>>> from machine import Pin
Breadboard
Breadboard
Mark
© 2023 Chick Commerce Pty Ltd