30. Multiprocessing Module

This Python snippets demonstrating the use of the multiprocessing module to run parallel processes for CPU-bound tasks:

1. Basic Multiprocessing Example

Copy

from multiprocessing import Process

def print_numbers():
    for i in range(5):
        print(f"Process: {i}")

if __name__ == "__main__":
    process = Process(target=print_numbers)
    process.start()
    process.join()

2. Passing Arguments to a Process

Copy

from multiprocessing import Process

def print_range(start, end):
    for i in range(start, end):
        print(f"Range {start}-{end}: {i}")

if __name__ == "__main__":
    process = Process(target=print_range, args=(1, 6))
    process.start()
    process.join()

3. Using a Pool of Processes

Copy


4. Process Synchronization with Lock

Copy


5. Sharing Data with Value and Array

Copy


6. Using a Queue for Process Communication

Copy


7. Using Manager for Shared State

Copy


8. Using Pool.apply_async for Asynchronous Processing

Copy


9. Using Process with Daemon

Copy


10. Using Barrier for Synchronization

Copy


These examples cover the basics of multiprocessing, including communication, synchronization, data sharing, process pools, and daemon processes.

Last updated