GIL (Global Interpreter Lock) allows only one thread to execute Python bytecode at a time.
Impact:
1import threading2import time34def cpu_bound(n):5 return sum(i * i for i in range(n))67# Threading (GIL limits CPU-bound)8start = time.time()9threads = [10 threading.Thread(target=cpu_bound, args=(10**7,))11 for _ in range(4)12]13for t in threads:14 t.start()15for t in threads:16 t.join()17print(f"Threading: {time.time() - start:.2f}s")1819# Multiprocessing (bypasses GIL)20from multiprocessing import Pool21start = time.time()22with Pool(4) as pool:23 pool.map(cpu_bound, [10**7] * 4)24print(f"Multiprocessing: {time.time() - start:.2f}s")
Solutions: