How to run same function on multiple threads in Python?
Last Updated :
26 Mar, 2021
In a large real-world application, the modules and functions have to go through a lot of input and output-based tasks like reading or updating databases, communication with different micro-services, and request-response with clients or peers. These tasks may take a significant amount of time to complete.
The time taken in serving a request and responding to the client is called latency and programmers need to reduce latency as much as possible. This leads to the need for parallel processing where our application is able to execute some function or method with different parameters for different clients. We can achieve that using threading. A thread can execute a function in parallel with other threads. Each thread shares the same code, data, and files while they have their own stack and registers.
Module Used:
In Python, we can create and run threads using the threading module. This module in python provides powerful and high-level support for threads.
Step-by-step Approach:
- Import the libraries. We will use threading module to create and run thread. To observe the output, we will create some delay using time module.
import threading
import time
- Define a sample function that we will use to run on different threads. In this example lets make a function that prints the squares of numbers in the given list.
# A sample function to print squares
def print_squares(thread_name, numbers):
for number in numbers:
print(thread_name, number**2)
# Produce some delay to see the output
# syntax: time.sleep(<time in seconds : float>)
time.sleep(1)
- Now create 2 or more threads using the threading.Thread class. The syntax of creating a thread is given below:
Syntax: thread_object = threading.Thread(target=<function name>, args=<tuple of arguments you want to pass>)
# Creating 3 threads that execute the same function with different parameters
thread1 = threading.Thread(
target=print_squares, args=("thread1", [1, 2, 3, 4, 5]))
thread2 = threading.Thread(
target=print_squares, args=("thread2", [6, 7, 8, 9, 10]))
thread3 = threading.Thread(
target=print_squares, args=("thread3", [11, 12, 13, 14, 15]))
- Now we need to start the execution. The Thread class has a start() method that transit the thread in running mode. The threads will run until they are not completed.
# Start the threads
thread1.start()
thread2.start()
thread3.start()
- We can block the program execution while all the threads are not completed using join() method of the Thread class.
# Join the threads before moving further
thread1.join()
thread2.join()
thread3.join()
Below is the full code:
Python3
# Import module
import threading
import time
# A sample function to print squares
def print_squares(thread_name, numbers):
for number in numbers:
print(thread_name, number**2)
# Produce some delay to see the output
time.sleep(1)
# Creating 3 threads that execute the same
# function with different parameters
thread1 = threading.Thread(target=print_squares,
args=("thread1", [1, 2, 3, 4, 5]))
thread2 = threading.Thread(target=print_squares,
args=("thread2", [6, 7, 8, 9, 10]))
thread3 = threading.Thread(target=print_squares,
args=("thread3", [11, 12, 13, 14, 15]))
# Start the threads
thread1.start()
thread2.start()
thread3.start()
# Join the threads before
# moving further
thread1.join()
thread2.join()
thread3.join()
Output:
Similar Reads
How to Call Multiple Functions in Python In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, weâll explore various ways we can call multiple functions in Python.The most straightforward way to call multiple functions is by executing them one after a
3 min read
Implementation of Queues in Multi-Threading in Python3 Implementation of Queues in Multi-Threading The Prerequisites Before reading this article, some important background reading is recommended to ensure that one is well equipped with the basic knowledge of threads as well as the basic knowledge of queues before trying to mix the two together. The offi
7 min read
How to create a new thread in Python Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes. In Python, there
2 min read
How to get the process id from Python Multiprocess? In this article, we will see how to get the process id from Python Multiprocess For this we should make use of method multiprocessing.current_process() to get the multiprocess id. Â Multiprocessing refers to the ability of a system to support more than one processor at the same time. Applications in
2 min read
Run Same Function in Parallel with Different Parameters - Python Running the same function in parallel with different parameters involves executing the function multiple times simultaneously, each time with a different set of inputs. For example, if we want to compute the square of each number in the list [0, 1, 2, 3, 4], instead of processing them one by one, ru
5 min read
Socket Programming with Multi-threading in Python Prerequisite : Socket Programming in Python, Multi-threading in PythonSocket Programming-> It helps us to connect a client to a server. Client is message sender and receiver and server is just a listener that works on data sent by client.What is a Thread? A thread is a light-weight process that d
3 min read
How does the Python Interpreter check thread duration? In Python, threads are a means of achieving concurrent execution. The Python interpreter employs a mechanism to manage and monitor the duration and execution of threads. Understanding how the Python interpreter handles thread duration is essential for developing efficient and responsive multithreade
3 min read
Python | How to lock Critical Sections This article aims how to lock the threads and critical sections in the given program to avoid race conditions. So, using Lock object in the threading library to make mutable objects safe to use by multiple threads. Code #1 : Python3 import threading class counter_share: ''' multiple threads can shar
4 min read
Implement Inter Thread Communication with Event( ) Method in Python Here we will start from the basics of what inter-thread communication is? Inter Thread Communication is the process of communicating requirements between one to another thread. In simple words sometimes one thread may be required to communicate to another thread depending on the requirements. This i
5 min read
Python | Communicating Between Threads | Set-2 Prerequisite: Communicating Between Threads | Set-1 If a thread needs to know immediately when a consumer thread has processed a particular item of data, one should pair the sent data with an Event object that allows the producer to monitor its progress as shown in the code given below - Code #1 : P
4 min read