Multithreading – Python

Brief Introduction

The Multithreading concept needs a proper understanding of 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.

Tutorial

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;

Code

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 below to your python Interpreter and save it. Then run the code and see the program’s prints on the console.

import threading
import time

## Function to print Time in Tasks (debug only)
def print_time(threadName, delay):
   while 1:
      time.sleep(delay)
      print ("%s: %s" % (threadName, time.ctime(time.time())))

## Structure for each Task
class myThread (threading.Thread):
   def __init__(self, threadID, name, interval):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.interval = interval   
   def run(self):
      while 1:
         print_time(self.name, self.interval)

# Create new threads
task1 = myThread(1, "thread_1", 2)
task2 = myThread(2, "thread_2", 4)
task3 = myThread(3, "thread_3", 1)

print("System Ready!!!!!!")

# Start new Threads
task1.start()
task2.start()
task3.start()

Result

Leave a Reply

Your email address will not be published. Required fields are marked *