Python Multiprocessing
Python's multiprocessing module allows you to create multiple processes that can run concurrently. This is useful for CPU-bound tasks where you want to take advantage of multiple processors or cores.
What is Multiprocessing?
Multiprocessing refers to the ability of a system to run multiple processes in parallel. In Python, the multiprocessing module helps you achieve parallel execution by using processes that run independently of each other. This can significantly improve performance for CPU-bound tasks.
How does Multiprocessing Work?
The multiprocessing module allows you to create processes that run in parallel. Each process has its own memory space and runs in its own Python interpreter. This makes it more efficient than using threads for CPU-bound tasks.
Example: Creating Multiple Processes
import multiprocessing
def print_square(number):
print(f'Square of {number} is {number * number}')
def print_cube(number):
print(f'Cube of {number} is {number * number * number}')
if __name__ == '__main__':
process1 = multiprocessing.Process(target=print_square, args=(4,))
process2 = multiprocessing.Process(target=print_cube, args=(3,))
process1.start()
process2.start()
process1.join()
process2.join()
Output
Explanation of the Code:
- The multiprocessing.Process class is used to create new processes. Each process is assigned a target function and its arguments. - start() begins the process, and join() ensures the main program waits for the processes to finish before continuing.
The multiprocessing module is a powerful way to perform parallel processing in Python. It is especially useful for CPU-bound tasks, allowing them to run on multiple CPU cores simultaneously for faster execution.