Building a Basic Multiprocessing Program
To get started with multiprocessing in Python, let's walk through the process of building a basic multiprocessing program.
Importing the Multiprocessing Module
The first step is to import the multiprocessing
module, which provides the necessary functions and classes for creating and managing processes.
import multiprocessing
Defining a Target Function
Next, you need to define a target function that will be executed by each process. This function can perform any task you want, such as performing a calculation, processing data, or executing a specific operation.
def worker_function(arg):
"""
A sample worker function that performs a simple calculation.
"""
result = arg * arg
print(f"Process {multiprocessing.current_process().name}: {result}")
Creating and Launching Processes
To create and launch processes, you can use the multiprocessing.Process
class. Here's an example:
if __name__ == "__main__":
## Create and start processes
process1 = multiprocessing.Process(target=worker_function, args=(2,))
process2 = multiprocessing.Process(target=worker_function, args=(3,))
process1.start()
process2.start()
## Wait for processes to finish
process1.join()
process2.join()
In this example, we create two processes, each of which executes the worker_function
with a different argument. The if __name__ == "__main__":
block ensures that the processes are only created and started when the script is run directly, and not when it's imported as a module.
The start()
method launches the processes, and the join()
method waits for the processes to complete before the main program can continue.
Observing the Output
When you run this program, you should see output similar to the following:
Process Process-1: 4
Process Process-2: 9
The output shows that the two processes executed the worker_function
concurrently, each with its own argument and result.
By understanding the basic structure of a multiprocessing program, you can now start building more complex applications that leverage the power of parallel processing in Python.