Multithreading – Python

Brief Introduction

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.

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

Your result:

Please follow and like us:
João Louro

Author: João Louro

Electrical Engineer with special interest in Embedded Systems, Real Time Operating Systems and Audio. With a degree in Electrical and Computer Engineering in the field of Electronics and Computers and currently studying Master's degree in Electrical Engineering.

Leave a Reply

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