×

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

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Python Functionalities of Pillow Module

This instructional exercise is about "Pillow" library, one of the significant libraries of python for picture control. Pillow library of python, is an easy to use and also open source...

14 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Exrex Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster...

4 minutes read.

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Socket Programming in Python

Socket Programming in Python In this tutorial, we will discuss network programming using Python programming language. We will explore all basic concept of network with Python script. Network Services in Python Python has...

9 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

How to Download Python

How to Download Python Python is the most renowned programming language and developers across the globe are working on projects that are made using Python and its libraries. Here we will...

4 minutes read.

Python Data Structures

Python Data Structures: Python is a programming language used worldwide for various fields such as building dynamic websites, artificial intelligence and many more. However, there is data that plays a...

18 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Python String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.