The Wayback Machine - https://web.archive.org/web/20240906224922/https://www.geeksforgeeks.org/python-run-same-function-in-parallel-with-different-parameters/
Open In App

Python – Run same function in parallel with different parameters

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to run the same function in parallel with different parameters. We can run the same function in parallel with different parameters using parallel processing.

The number of tasks performed by the program can be increased by parallel processing, which decreases the total processing time. These assist in addressing large-scale issues. Using the standard multiprocessing module, by creating child processes, we can effectively parallelize simple tasks. This module provides an easy-to-use interface and includes a set of task submission and synchronization handling utilities.

Approach:

  • We may construct a process running independently by subclassing the multiprocessing process. We can initialize the resource by extending the __init_ method, and we can write the code for the subprocess by implementing the Process.run() method. We see how to construct a process in the code below, which prints the assigned id.
  • We need to initialize our process object and invoke the Process.start() method in order to spawn the process. Here, Process.start() will create a new process and invoke a method called Process.run().
  • The code after p.start() is executed immediately before process p completes the mission. You may use Process.join to wait for task completion().

Let’s understand this with some examples.

Example 1: 

Python
import multiprocessing
import time

# Process class
class Process(multiprocessing.Process):
    def __init__(self, id):
        super(Process, self).__init__()
        self.id = id

    def run(self):
        time.sleep(1)
        print("I'm the process with id: {}".format(self.id))


if __name__ == '__main__':
    p = Process(0)

    # Create a new process and invoke the
    # Process.run() method
    p.start()

    # Process.join() to wait for task completion.
    p.join()
    p = Process(1)
    p.start()
    p.join()

Output:

We can also run the same function in parallel with different parameters using the Pool class. For parallel mapping, We have to first initialize multiprocessing.Pool() object. The first argument is the number of workers; if not given, that number will be equal to the number of elements in the system.

Example 2:

Let see by an example. In this example, we will see how to pass a function that computes the square of a number. Using Pool.map() we can map the function to the list and passing the function and the list of inputs as arguments, as follows:

Python
import multiprocessing
import time

# square function
def square(x):
    return x * x


if __name__ == '__main__':

    # multiprocessing pool object
    pool = multiprocessing.Pool()

    # pool object with number of element
    pool = multiprocessing.Pool(processes=4)

    # input list
    inputs = [0, 1, 2, 3, 4]

    # map the function to the list and pass
    # function and input list as arguments
    outputs = pool.map(square, inputs)

    # Print input list
    print("Input: {}".format(inputs))

    # Print output list
    print("Output: {}".format(outputs))

Output:

Example 3:

Python
from multiprocessing import Pool


def print_range(range):
  
    # print range
    print('From {} to {}:'.format(range[0], range[1]))


def run_parallel():
  
    # list of ranges
    list_ranges = [[0, 10], [10, 20], [20, 30]]

    # pool object with number of elements in the list
    pool = Pool(processes=len(list_ranges))

    # map the function to the list and pass 
    # function and list_ranges as arguments
    pool.map(print_range, list_ranges)

# Driver code
if __name__ == '__main__':
    run_parallel()

Output:

Python – Run same function in parallel with different parameters – FAQs

How to call the same function with different parameters in Python?

To call the same function with different parameters, simply invoke the function multiple times with different arguments.

Example:

def greet(name):
print(f"Hello, {name}!")

# Calling the same function with different parameters
greet("Alice")
greet("Bob")
greet("Charlie")

How to call the same function in parallel in Python?

To call the same function in parallel, use the concurrent.futures.ThreadPoolExecutor or ProcessPoolExecutor for multithreading or multiprocessing.

Example with ThreadPoolExecutor:

from concurrent.futures import ThreadPoolExecutor

def greet(name):
print(f"Hello, {name}!")

names = ["Alice", "Bob", "Charlie"]

with ThreadPoolExecutor() as executor:
executor.map(greet, names)

Example with ProcessPoolExecutor:

from concurrent.futures import ProcessPoolExecutor

def greet(name):
print(f"Hello, {name}!")

names = ["Alice", "Bob", "Charlie"]

with ProcessPoolExecutor() as executor:
executor.map(greet, names)

How to parallelize a function in Python?

To parallelize a function, use concurrent.futures or multiprocessing to run the function concurrently.

Example with concurrent.futures:

from concurrent.futures import ThreadPoolExecutor

def compute(x):
return x * x

inputs = [1, 2, 3, 4, 5]

with ThreadPoolExecutor() as executor:
results = list(executor.map(compute, inputs))
print(results)

Example with multiprocessing:

from multiprocessing import Pool

def compute(x):
return x * x

inputs = [1, 2, 3, 4, 5]

with Pool() as pool:
results = pool.map(compute, inputs)
print(results)

How to run multiple tasks in parallel in Python?

To run multiple tasks in parallel, use concurrent.futures.ThreadPoolExecutor or ProcessPoolExecutor.

Example with ThreadPoolExecutor:

from concurrent.futures import ThreadPoolExecutor

def task(number):
print(f"Task {number}")

tasks = [1, 2, 3, 4, 5]

with ThreadPoolExecutor() as executor:
executor.map(task, tasks)

Example with ProcessPoolExecutor:

from concurrent.futures import ProcessPoolExecutor

def task(number):
print(f"Task {number}")

tasks = [1, 2, 3, 4, 5]

with ProcessPoolExecutor() as executor:
executor.map(task, tasks)

How to run a Python script multiple times in parallel?

To run a Python script multiple times in parallel, use the subprocess module to start new processes.

Example:

import subprocess

scripts = ["script1.py", "script2.py", "script3.py"]

processes = [subprocess.Popen(["python", script]) for script in scripts]

for process in processes:
process.wait()


Similar Reads

Run Tests in Parallel with PyTest
Testing is one of the key factors of the application and code development. It is necessary whenever a team or an individual aims for a stable and performance-efficient product in a production environment. It also acts as a confidence booster for the developers as well as makes code modifications and debugging easier. There are different testing fra
4 min read
How to run same function on multiple threads in Python?
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 resp
3 min read
Google Cloud Platform - Running Different Versions of Python on Google Cloud Run
Problem Statement: Rinki works for StoreCraft(Say) as a site reliability engineer, where she's on-call maintaining their custom storefront. StoreCraft's systems are developed in-house in Python and have been running on virtual machines for years, a set up that evolved as StoreCraft's businesses did. These virtual machines use slightly different ver
3 min read
How to get list of parameters name from a function in Python?
In this article, we are going to discuss how to get list parameters from a function in Python. The inspect module helps in checking the objects present in the code that we have written. We are going to use two methods i.e. signature() and getargspec() methods from the inspect module to get the list of parameters name of function or method passed as
3 min read
How to pass optional parameters to a function in Python?
In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function by either passing those optional parameters or ju
5 min read
Run function from the command line In Python
Python is a flexible programming language with a wide range of uses that one of Python’s most useful ones is its ability to execute functions from the command line. Especially this feature is very useful when it comes to automation and scripting etc. In this article, I’ll explain how to execute a Python function from the command line. Defining a Fu
4 min read
Why does Python code run faster in a function?
Python, renowned for its simplicity and readability, has some interesting performance characteristics that might not be immediately obvious to beginners. One such characteristic is that code often runs faster when it's inside a function. This behavior can be puzzling at first, but it becomes clear when we delve into the underlying mechanics of how
4 min read
How to apply different titles for each different subplots using Plotly in Python?
Prerequisites: Python Plotly In this article, we will explore how to apply different titles for each different subplot. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears. It provides us
2 min read
Data Classes in Python | Set 2 (Decorator Parameters)
Prerequisite: Data Classes in Python | Set 1 In this post, we will discuss how to modify the default constructor which dataclass module virtually makes for us. dataclass() decorator - @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) By changing the values of these parameters, we can modify the b
4 min read
Crontab - Running a Python script with parameters
Scheduling python scripts with crontab is fundamental when it comes to automating tasks using python. We will see how to schedule python scripts and pass the necessary parameters as well. The Cron job utility is a time-based job scheduler in Unix. It allows the user to run the file at a given time and date. And crontab is a list of commands that yo
2 min read
Deep dive into Parameters and Arguments in Python
There is always a little confusion among budding developers between a parameter and an argument, this article focuses to clarify the difference between them and help you to use them effectively. Parameters:A parameter is the variable defined within the parentheses during function definition. Simply they are written when we declare a function. Examp
3 min read
Decorators with parameters in Python
Prerequisite: Decorators in Python, Function Decorators We know Decorators are a very powerful and useful tool in Python since it allow programmers to modify the behavior of functions or classes. In this article, we will learn about the Decorators with Parameters with the help of multiple examples. Python functions are First Class citizens which me
5 min read
Why do Python lambda defined in a loop with different values all return the same result?
In this article, we are going to learn why Python lambda defined in a loop with different values all return the same result. In this article, we will explore the reasons behind this behavior and discuss how to avoid it. We will start by looking at how lambda functions are defined and executed, and how they capture the values of variables that are u
6 min read
Parallel Processing in Python
Parallel processing can increase the number of tasks done by your program which reduces the overall processing time. These help to handle large scale problems. In this section we will cover the following topics: Introduction to parallel processing Multi Processing Python library for parallel processing IPython parallel framework Introduction to par
7 min read
Parallel Coordinates Plot using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. Plotly is an interactive visualization library. Parallel Coordinates Plot Parallel coordinates
2 min read
PyQt5 – Different padding size at different edge of Label
In this article, we will see how we can add different padding size at different edges. Below is a image of label with normal padding and a label with different padding size at different edge. In order to do this we will use setStyleSheet() method and describe padding length for each edge. Syntax : label.setStyleSheet("border :3px solid black;" "pad
2 min read
PyQt5 - Setting different toolTip to different item of ComboBox
In this article we will see how we can set different tooltip to the different items of the combo box. We can set tooltip to the combo box with the help of setToolTip method and for setting tooltip to the view part we have to use view object with this method. Below is the representation of how individual item tool tip look like. In order to do we ha
2 min read
wxPython - SetMargins() with wx.Size parameters
In this article we are going to learn about SetMargins() function associated with wx.ToolBar class of wxPython. Similarly with previous article SetMargins() function set the margins for the toolbar. But the only difference is rather taking two different parameters x and y it takes using wx.Size parameter. Syntax: wx.ToolBar.SetMargins(self, size) P
1 min read
GET Request Query Parameters with Flask
In this article, we will learn how we can use the request object in a flask to GET Request Query Parameters with Flask that is passed to your routes using Python. As we know, Flask is a web development framework written in Python, and the flask is widely used as a web framework for creating APIs (Application Programming Interfaces). Or we can say i
4 min read
How to Handle Missing Parameters in URL with Flask
In this article, we will discuss how to handle missing parameters in URLs with Flask. It is a web framework that offers libraries for creating simple web applications in Python. In Flask, URL parameters, commonly referred to as "query strings," you can organize extra information for a certain URL. Parameters are added to the end of a URL after a ‘?
4 min read
Multi-value Query Parameters with Flask
Flask is a micro-framework written in Python. It is lightweight, and easy to use, making it famous for building RESTful APIs. In this article we are going to see how to use Multi-value query parameters with flask. You can know more about it here. Let's understand the basics with an example: C/C++ Code from flask import Flask app = Flask(__name__) @
2 min read
RBF SVM Parameters in Scikit Learn
Scikit Learn is a popular machine-learning library in Python, and it provides a powerful implementation of Support Vector Machines (SVMs) with the Radial Basis Function (RBF) kernel. RBF kernel is a popular choice for SVM because it can handle non-linear decision boundaries, making it suitable for a wide range of classification tasks. When using RB
9 min read
FastAPI - Cookie Parameters
FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, we’ll walk you through the steps on how to use Cookie in FastAPI. What are Cookies?Cookies are pieces of data stored on the client browser by the server when the user is browsing the web page. Multiple cookies ca
4 min read
Send Parameters to POST Request FastAPI
In the world of web development and API creation, sending parameters via a POST request is a fundamental operation. FastAPI, a modern Python web framework, simplifies this process and allows developers to build efficient and scalable APIs. In this article, we will explore the theory and practical aspects of sending parameters to a POST request usin
3 min read
FastAPI - Header Parameters
FastAPI is the fastest-growing Python API development framework, It is easy to lightweight, and user-friendly and It is based on standard Python-type hints, which makes it easier to use and understand. FastAPI supports header parameters, these are used to validate and process incoming API calls. In this article, you will learn everything you need t
4 min read
POST Query Parameters in FastAPI
FastAPI is a powerful and efficient Python web framework for building APIs with ease. For most of the applications getting data from a user is done through a POST request and this is a common task for developers is consume query parameters from POST requests. In this article, we'll explore the concepts behind this process and provide practical exam
4 min read
FastAPI - Path Parameters
In this exploration, we'll dive into the realm of FastAPI Path Parameters, unraveling their pivotal role in constructing dynamic and versatile APIs. FastAPI stands out as a contemporary web framework celebrated for its speed, tailor-made for crafting APIs in Python 3.7 and beyond. Leveraging standard Python-type hints, FastAPI simplifies the compre
4 min read
FastAPI - Query Parameters
In this article, we will learn about FastAPI Query Parameters, what are query parameters, what they do in FastAPI, and how to use them. Additionally, we will see examples of query parameters for best practices. What is FastAPI - Query Parameters?Query parameters stand as a formidable asset in bolstering the flexibility and usability of an API. Thei
6 min read
How to Add URL Parameters to Django Template URL Tag?
When building a Django application, it's common to construct URLs dynamically, especially when dealing with views that require specific parameters. The Django template language provides the {% url %} template tag to create URLs by reversing the URL patterns defined in the urls.py file. This tag becomes especially useful when we need to pass additio
4 min read
TensorFlow - How to stack a list of rank-R tensors into one rank-(R+1) tensor in parallel
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. TensorFlow provides build in methods to stack a list of rank-R tensors into one rank-(R+1) tensor in parallel. Methods Used: parallel_stack: This method accepts a list of Tensors and returns a Tensor with all values stac
2 min read
Practice Tags :