Python – Run same function in parallel with different parameters
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- 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.
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.
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: