×

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it to perform multi-tasking. Before we understand more about multithreading, first, let’s understand threading.

What is a thread?

Thread can be explained as the execution of the smallest sequence of instructions that can be executed independently by a scheduler of an operating system. It is the basic unit of CPU utilisation. A process can be defined as a program that is being executed, and all processes have three main components, which are:

  1. A program that will be executed.
  2. The data needed for that program, like variables, workspace, buffers, etc.
  3. The state of the process.

Now, a thread is the smallest unit of processing that will get executed in an operating system. It is an entity in the process which is scheduled for execution. It is a sequence of those instructions in the code that can be executed independently in any other program. It contains all the information in a Thread Control Block (TCB).

These are the information that gets stored in a TCB:

  • Parent Process Pointer: It contains a pointer pointing to the Process Control Block (PCB) where the threads live on.
  • Thread ID: It is the unique id assigned to all the new threads.
  • Thread State: It is the state of the thread, which can be running, ready, starting, waiting and done.
  • Program counter: It is a register which stores the address of the instruction being executed.
  • Register Set:  It is the register assigned to the thread for computation.
  • Stack Pointer: It is the pointer pointing to the stack which stores the local variables.

What is Multithreading?

Multithreading enables the CPU to execute different threads concurrently inside a process. In multithreading, we share the data with the main thread and, therefore, can easily communicate or share information with each other. Threads are very light-weighted processes which means they don’t need a lot of memory. In multi-thread, all the threads have their own register set and local variables (stored in a stack), but they all share global variables and the program code.

Multithreading can be achieved by switching between threads. This process of switching is known as Context Switching. In this, the state of one thread is saved while the other is executed or loaded.

Starting a thread in python

thread.start_new_thread ( function, args[, kwargs] )

This method is used to create very fast and efficient threads. Here, args is the argument or a tuple of argument while kwargs is a keyword argument.

In python, we use the threading module for creating and spawning multiple threads in a program.

Let’s understand with a very simple example.

Example:

import threading
  
def triple(num):
   # function to print triple of given num
    print("Triple: {}".format(3 * num))
  
def double(num):
   # function to print double of given num
    print("Double: {}".format(2 * num))
  
if __name__ == "__main__":
    # creating thread
    th1 = threading.Thread(target=double, args=(10,))
    th2 = threading.Thread(target=triple, args=(10,))
  
    # starting thread 1
    th1.start()
    # starting thread 2
    th2.start()
  
    # wait until thread 1 is completely executed
    th1.join()
    # wait until thread 2 is completely executed
    th2.join()
  
    # both threads completely executed
    print("Done!")

Output

Double: 20
Triple: 30
Done!

Explanation

In the above line of code, we have imported the threading module using the command import threading. After that, we created two threads with different target functions, which are th1 and th2. After creating the threads, we used the start method to start the thread, which is th1.start and th2.start. In this code, we have used the join method to stop the execution of the main thread until the thread is executed. Because of this, the first thread, th1, will be executed, then th2, and then we will come out of the program.

Threading Module

A threading module in python gives very powerful and high-level support for the threads in the program. It gives some additional modules like-

  • threading.activeCount() : it returns the total number of active threads.
  • threading.currentThread(): It returns the total number of threads in the caller control.
  • threading.enumerated(): It returns a list of threads that are active presently.

Some additional methods that a threading module has are:

  • run(): It is the entry point of the thread.
  • start(): It starts a thread after calling the run method.
  • join([time]): It waits for a thread to terminate.
  • isAlive(): It checks if a method is still executing or not.
  • getName(): It returns the name of the thread.
  • setName(): It sets the name of the thread.

Related Topics

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

How to plot a Histogram in Python

A Histogram is used to represent a given data provided as a chunk. This histogram is a graphical representation that uses bars to indicate the ranges of the data. In...

4 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

Python List Size

Introduction The list data type in Python is an ordered, flexible collection. A list may also contain duplicate entries. To get the size of any object, use the len() function in...

6 minutes read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Convert List to Array in Python

What is List in Python? In Python, a list is a built-in data structure that stores a collection of items. The items in a list can be of any data type,...

3 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

Reverse a sentence In Python

Introduction The built-in reverse() function is not supported by the Python string library. As we know, a Python string is defined as a set of Unicode characters and Python provides various...

4 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.