×

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

Sentence to python vector

Conversion of a Sentence to Vector in Python Before starting the tutorial, let’s just recap about the vector and the respective package that has to be imported in Python. Python Vector: Putting simply,...

3 minutes read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Pltpcolor in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python lock

Before understanding the concept of Python-lock we need to understand what kind if condition we require to implement the locks in Python. Let us start with multithreading and its implementation...

5 minutes read.

Mrcnn Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 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.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

How to Substring a String in Python

String Unicode characters collection is referred to as a String. It consists of a succession of characters, including alphanumeric and special characters. Substring: Core Concept A substring is a piece of a string....

5 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python String strip() method

Python String strip() method The string. strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to...

1 minute read.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Get Bounding Box Co-ordinates 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 way....

6 minutes read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.