⚡ Multiprocessing

Last Updated: 08 Sept 2025

  • Multiprocessing means running multiple processes in parallel.
  • Each process has its own memory space (independent).
  • Best for CPU-bound tasks (heavy calculations).
  • Same as threads, but here it runs in a new process.

Hinglish Tip 🗣: "Thread ek process ke andar hota hai, par multiprocessing me har ek process apna alag program ki tarah chalta hai."


✏ Creating a Process

We use multiprocessing.Process().

from multiprocessing import Process
import time

def worker():
    print("Worker process running")
    time.sleep(2)

# create process
p = Process(target=worker)

# start process
p.start()

# wait for it to finish
p.join()

print("Main program finished")

Checking Current Process

from multiprocessing import Process, current_process

def show_name():
    print("Running in:", current_process().name)

p = Process(target=show_name, name="MyProcess")
p.start()
p.join()

⚙ Using Pool of Workers

multiprocessing.Pool() is useful when we want to run the same function on multiple inputs.

from multiprocessing import Pool

def square(x):
    return x * x

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

👉 pool.map(func, iterable) works like map(), but in parallel.