×

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

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

PyShark in 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....

4 minutes read.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.

Managing Multiple Python Versions With pyenv

Introduction If you had ever wished to assist to an application that makes use of several different Python versions but weren't sure whether you would quickly test them all? Do you...

4 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Excel Automation with Python

Data analysis is the upcoming technology in the IT sector; this data analysis can be performed easily with the help of data frames or by using excel sheets. The data...

4 minutes read.

What is the re.sub() function in Python

There. sub () function is used to return a string by replacing the occurrences of a specific character or pattern with a replacement string. To use this function, import the...

3 minutes read.

Python's Qstandarditemmodel

Python More interactive and user-friendly than any other programming language is Python. Many libraries are used by the python programming language to speed up procedures. Python can be used to develop...

3 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Python divmod() function

Python divmod() function The divmod() function in Python returns a tuple containing the quotient  and the remainder when parameter ‘a’ (divident) is divided by parameter ‘b’ (divisor). Syntax: divmod(a, b) Parameter a: This parameter represents a number you...

1 minute read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

Python Setup guide and installation

Python Installation guide Step by Step Python is widely used high-level programming language. The first version of Python was launched in 1991. Since then, Python has been gaining popularity. It is considered as...

4 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

Paramiko Python Example

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.