Junior — Middle
How does the GIL restriction affect the parallel work of Python programs?
sobes.tech AI
Answer from AI
GIL (Global Interpreter Lock) in CPython is a mechanism that ensures only one thread executes Python bytecode at a time. This affects parallel execution as follows:
- Multithreading does not improve performance for CPU-bound tasks. Even with multiple threads, they cannot utilize multiple CPU cores for Python code execution.
- I/O-bound tasks benefit from multithreading. Threads waiting for I/O release the GIL, allowing others to run.
To bypass GIL, often use:
- Multiprocessing (the
multiprocessingmodule), where each process has its own interpreter and GIL. - Use C extensions that can release the GIL during heavy computations.
Example:
import threading
import time
def cpu_bound():
count = 0
for _ in range(10**7):
count += 1
threads = [threading.Thread(target=cpu_bound) for _ in range(4)]
start = time.time()
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Time: {time.time() - start} seconds")
Despite 4 threads, execution time is almost the same as a single thread due to GIL.