Middle
What is GIL in Python and why do we need to know about it?
sobes.tech AI
Answer from AI
GIL (Global Interpreter Lock) is a mechanism in CPython that ensures only one thread executes Python bytecode at a time. This is done to simplify memory management and prevent issues with thread safety.
Why know about GIL:
- It limits the efficiency of multithreaded execution of CPU-bound tasks in Python, as threads cannot run in parallel on multiple cores.
- For tasks requiring parallelism, multiprocessing (processes) or external libraries that bypass GIL (e.g., numpy, implemented in C) are often used.
Example: if you run multiple threads for computations, they will work sequentially due to GIL, not in parallel.
import threading
def cpu_bound_task():
count = 0
for i in range(10**7):
count += i
threads = []
for _ in range(4):
t = threading.Thread(target=cpu_bound_task)
t.start()
threads.append(t)
for t in threads:
t.join()
In this example, 4 threads will not provide a performance increase due to GIL.