Multiprocessing

Multiprocessing in Python: Imagine you have a supercomputer with 16 brains (Cores). Threading is like having one brain try to think about 5 things at once.

Concept Explanation

Imagine you have a supercomputer with 16 brains (Cores).

  • Threading is like having one brain try to think about 5 things at once. It's fast at switching, but it's still just one brain.
  • Multiprocessing is like hiring 16 separate workers, each with their own desk, their own computer, and their own hammer. They don't have to share anything.

In Python, the Multiprocessing module allows you to create separate "Processes." Each process has its own private memory and its own Python interpreter. This allows you to perform Parallelism—truly running many things at the exact same millisecond.


Syntax or Core Structure

The Process class

Similar to threading, you define a target function and start it.

from multiprocessing import Process
import os

def info(title):
    print(f"{title}: Process ID {os.getpid()}")

if __name__ == '__main__':
    p = Process(target=info, args=('Child',))
    p.start()
    p.join() # Wait for it to finish

The Pool class

A more powerful way to handle many tasks at once.

from multiprocessing import Pool

def square(n):
    return n * n

if __name__ == "__main__":
    with Pool(processes=4) as pool:
        results = pool.map(square, [1, 2, 3, 4, 5])
        print(results)

Code Example #1 (Basic)

Checking how many CPU cores your computer actually has.

import multiprocessing

cores = multiprocessing.cpu_count()
print(f"My computer has {cores} CPU cores available for work.")

Code Example #2 (Intermediate)

Sharing data between processes using a Queue.

from multiprocessing import Process, Queue

def producer(q):
    q.put("Data from Child")

if __name__ == "__main__":
    q = Queue()
    p = Process(target=producer, args=(q,))
    p.start()
    print(f"Parent received: {q.get()}")
    p.join()

Real World Example

Image Batch Processor: Resizing 1,000 high-resolution photos.

import multiprocessing
import time

def resize_image(name):
    # Simulate heavy CPU work
    print(f"Resizing {name}...")
    time.sleep(1)
    return f"{name}_resized"

if __name__ == "__main__":
    images = [f"img_{i}.jpg" for i in range(10)]
    
    start = time.time()
    with multiprocessing.Pool() as pool:
        pool.map(resize_image, images)
    
    end = time.time()
    print(f"Total time with multiprocessing: {end-start:.2f}s")

Common Mistakes

  1. Forgetting if __name__ == '__main__':: On Windows, if you don't include this line, your program will spawn billions of processes and crash your computer instantly. Always use this wrapper.
  2. Large Data Transfer: Sending massive amounts of data (like a 4GB list) between processes is slow because Python has to "pickle" (serialize) and "unpickle" the data.
  3. Memory Usage: Each process uses its own RAM. Spawning 100 processes might use up all your computer's memory.

Best Practices

  • Match Process Count to Cores: Usually, setting processes=multiprocessing.cpu_count() gives the best performance.
  • Avoid Shared State: Try to give each process everything it needs so it doesn't have to talk back to the main program until it’s finished.
  • Use Pools: For batch jobs, Pool.map is much cleaner than managing Process objects manually.

Practice Exercises

  1. Core Count: Run a script that prints your CPU count and creates that exact number of processes.
  2. Parallel Square: Use a Pool to calculate the squares of all numbers from 1 to 1,000. Measure the time difference between this and a normal list comprehension.
  3. Process Identifiers: Write a function that prints its os.getpid(). Run it in 4 different processes and verify that every ID is unique.