Certainly! Testing multiprocessing in Python can be an interesting and useful task for leveraging multiple CPU cores to perform parallel processing. Here is a basic example that demonstrates how to use the multiprocessing module in Python:
import multiprocessing
import time
# This is the worker function that each process will execute
def worker(num):
"""thread worker function"""
print(f'Worker: {num}')
time.sleep(2) # Simulate a time-consuming task
return num * num
if __name__ == '__main__':
# Determine the number of CPU cores available
cpu_count = multiprocessing.cpu_count()
print(f"Number of CPU cores: {cpu_count}")
# Create a pool of worker processes
pool = multiprocessing.Pool(processes=cpu_count)
# Create a list of inputs to be processed
inputs = list(range(10))
# Map the worker function to the inputs, distributing work across the pool
results = pool.map(worker, inputs)
# Close the pool and wait for the work to finish
pool.close()
pool.join()
# Display the results
print(f'Results: {results}')
Explanation:
-
Worker Function: The worker function is defined to perform a time-consuming task (simulated here with a time.sleep(2)). This function takes an input, in this case, num, and returns the square of the input.
-
Main Section:
- The
if __name__ == '__main__': guard is necessary to prevent the worker function from being executed immediately when the module is imported (an important consideration for Windows).
- We determine the number of CPU cores using
multiprocessing.cpu_count().
- We create a
Pool of worker processes, with the number of processes equal to the number of CPU cores.
- We generate a list of inputs to be processed (in this case, a list of integers from 0 to 9).
- The
pool.map() function is used to distribute the workload across the pool of worker processes.
- We close the pool and wait for all processes to complete with
pool.close() and pool.join().
- Finally, we print the results of the computation.
Running the Code
To run this program, save the code in a file (e.g., multiprocessing_test.py) and execute it in a Python environment. The output will demonstrate the worker processes operating in parallel and the results of their computations.
Note
- Multiprocessing creates separate memory space for each process, which differentiates it from threading where threads share the same memory space.
- Make sure to include the necessary import statements and error handling in a real-world application to improve robustness.