Sobes.tech
Middle

What is GIL in Python and what limitations does it impose on multithreading?

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 concurrent access to objects.

Restrictions imposed by GIL on multithreading:

  • Threads cannot efficiently utilize multiple CPU cores for executing Python code simultaneously.
  • Multithreading in Python is more suitable for I/O-bound tasks, where threads often block, rather than for CPU-bound tasks.
  • For CPU-bound tasks, multiprocessing is often used to bypass the GIL restriction.

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"Execution time: {time.time() - start} seconds")

Despite having 4 threads, the execution time will be close to sequential, due to the GIL.