Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the difference between threading and multiprocessing in Python? Python में threading और multiprocessing में क्या अंतर है?

Answer
Aspectthreadingmultiprocessing
MemoryShared memory spaceSeparate memory per process
GIL impactLimited by GIL for CPU-bound workBypasses GIL - true parallelism
OverheadLightweight, fast to createHeavier, slower to create (new process)
Best forI/O-bound tasks (network, files)CPU-bound tasks (computation)
import threading
import multiprocessing
import time

def cpu_task(n):
    return sum(i * i for i in range(n))

# Threading - limited by GIL for CPU-bound work
start = time.time()
threads = [threading.Thread(target=cpu_task, args=(10_000_000,)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(f'Threading: {time.time() - start:.2f}s')

# Multiprocessing - true parallelism across CPU cores
if __name__ == '__main__':
    start = time.time()
    processes = [multiprocessing.Process(target=cpu_task, args=(10_000_000,)) for _ in range(4)]
    for p in processes: p.start()
    for p in processes: p.join()
    print(f'Multiprocessing: {time.time() - start:.2f}s')
    # Noticeably FASTER on a multi-core machine because each process
    # has its own Python interpreter and GIL - no contention between them

# Sharing data between processes requires special mechanisms (unlike threads)
from multiprocessing import Queue
q = Queue()
q.put('hello')
print(q.get())  # 'hello' - processes don't share memory, so need explicit IPC
पहलूthreadingmultiprocessing
MemoryShared memoryअलग memory per process
GIL impactCPU-bound काम में limitedGIL bypass - true parallelism
Overheadहल्का, तेज़ बनता हैभारी, धीमा बनता है
सबसे अच्छाI/O-bound tasksCPU-bound tasks
import threading
import multiprocessing
import time

def cpu_task(n):
    return sum(i * i for i in range(n))

# Threading - GIL से limited
start = time.time()
threads = [threading.Thread(target=cpu_task, args=(10_000_000,)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()

# Multiprocessing - true parallelism
if __name__ == '__main__':
    start = time.time()
    processes = [multiprocessing.Process(target=cpu_task, args=(10_000_000,)) for _ in range(4)]
    for p in processes: p.start()
    for p in processes: p.join()
    # Multi-core पर काफ़ी तेज़

from multiprocessing import Queue
q = Queue()
q.put('hello')
print(q.get())

Was this answer clear?