×

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

Enumerate() Function in Python

The enumerate() function in Python is used to convert a data collection object into an enumerate object. It returns an object that contains a counter as a key for each...

3 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Spell Corrector GUI using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

Shallow Copy and Deep Copy in Python

Shallow Copy and Deep Copy in Python In this section, we will learn about the Shallow Copy and Deep Copy in the Python program. But before going through the topic, we...

6 minutes read.

Python Set symmetric_difference_update() method

Python Set symmetric_difference_update() method The set.symmetric_difference_update() method in Python updates the original set by removing items that are present in both sets and inserting the other items of the set. Syntax set.symmetric_difference_update(set1) Parameter set- This parameter represents the first...

2 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Python pynmea2

Define Pynmea2 Python Programming Language: 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...

4 minutes read.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

3 minutes read.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

Python program to find factorial of a given number

Python program to find factorial of a given number Factorial is a non-negative integer. It is the product of all positive integers from 1 to the number we are going to...

3 minutes read.

How to print in the same line in Python?

How to print in the same line in python By default, the print function in Python takes us to the next line and prints the desired statement in the output. In this...

5 minutes read.