The Multithreading concept needs proper understanding these two terms – a process and a thread. A process can be divided into independent units know as threads, and a process is a program that is running.
Multithreading allows the execution of tasks periodically, widely used in applications that need to comply with execution times, as is the case with bluetooth, voip, real time images or simply periodic sensor measurements.
In this tutorial I am going to show you how to multithreading using python as a programming language. You can use any python interpreter and any device with python (PC, Raspberry PI …).
You need to install threading and time libraries, using the next lines:
– pip install threading;
– pip install time;
As you can see in the code below, there is a class called “myThread ()”, this class defines your task code, this is where you insert the code you want to execute in the task, more precisely within the ‘while 1‘.
When you create your threads, you can define the task execution time interval, as you can see in the code below (myThread(1, “thread_1”, 2)), the last argument is the time interval, the first argument is the ID number of the task and “thread_1” is the name of the task.
Copy the code bellow to your python Interpreter and save it. Then run the code and see the program’s prints on the console.
## Function to print Time in Tasks (debug only)
def print_time(threadName, delay):
print ("%s: %s" % (threadName, time.ctime(time.time())))
## Structure for each Task
class myThread (threading.Thread):
def __init__(self, threadID, name, interval):
self.threadID = threadID
self.name = name
self.interval = interval
# Create new threads
task1 = myThread(1, "thread_1", 2)
task2 = myThread(2, "thread_2", 4)
task3 = myThread(3, "thread_3", 1)
# Start new Threads