W3docs

Multiprocessing vs Threading Python

Here is a code snippet for multiprocessing in Python:

Below is an example of multiprocessing in Python:

An example of multiprocessing in Python

import multiprocessing

def worker(num):
    """process worker function"""
    print(f'Worker: {num}')

jobs = []
for i in range(5):
    p = multiprocessing.Process(target=worker, args=(i,))
    jobs.append(p)
    p.start()

for p in jobs:
    p.join()

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Below is an example of threading in Python:

An example of threading in Python

import threading

def worker(num):
    """thread worker function"""
    print(f'Worker: {num}')

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

The main difference between the two is that multiprocessing creates separate processes for each function call, while threading creates threads within the same process. This means that multiprocessing allows for true parallelism on systems with multiple cores, bypassing the Global Interpreter Lock (GIL) for CPU-bound tasks. Threading, on the other hand, allows for concurrent execution and is best suited for I/O-bound tasks where threads can wait for external operations without blocking the main program.