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

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

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


4. Process Synchronization with Lock


5. Sharing Data with Value and Array


6. Using a Queue for Process Communication


7. Using Manager for Shared State


8. Using Pool.apply_async for Asynchronous Processing


9. Using Process with Daemon


10. Using Barrier for Synchronization


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

Last updated