multiprocessing runs code in separate processes, bypassing the GIL.
1from multiprocessing import Process, Pool, Queue23# Process — manual management4def worker(n):5 return n * n67p = Process(target=worker, args=(5,))8p.start()9p.join()1011# Pool — managed process pool12with Pool(4) as pool:13 results = pool.map(worker, range(10))14 print(results) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]1516# Parallel map17results = pool.map(cpu_intensive, large_dataset)1819# Async map20async_result = pool.map_async(worker, range(10))21print(async_result.get())
Communication between processes:
1from multiprocessing import Queue23q = Queue()4q.put(data) # Send5data = q.get() # Receive
When to use: