Subjects

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

What is the Global Interpreter Lock (GIL) and why does it matter? Global Interpreter Lock (GIL) क्या है और यह क्यों important है?

Answer

The GIL is a mutex in CPython that allows only ONE thread to execute Python bytecode at a time, even on multi-core machines. It exists to make CPython's memory management simpler and thread-safe.

import threading
import time

def cpu_bound_task():
    count = 0
    for i in range(50_000_000):
        count += 1
    return count

# Running 2 threads for a CPU-bound task
start = time.time()
t1 = threading.Thread(target=cpu_bound_task)
t2 = threading.Thread(target=cpu_bound_task)
t1.start(); t2.start()
t1.join(); t2.join()
print(f'Threaded: {time.time() - start:.2f}s')
# Due to the GIL, this does NOT run twice as fast on a multi-core CPU -
# threads take turns holding the GIL, so CPU-bound work barely benefits

# Single-threaded equivalent runs at similar or even better speed
start = time.time()
cpu_bound_task()
cpu_bound_task()
print(f'Sequential: {time.time() - start:.2f}s')
# Often comparable to the threaded version, because of GIL contention overhead
Workload typeGIL impact
CPU-bound (heavy computation)Threads don't help - GIL serializes execution
I/O-bound (network, disk, waiting)Threads DO help - GIL is released during I/O waits

GIL CPython में एक mutex है जो एक समय में सिर्फ एक thread को Python bytecode execute करने देता है, multi-core machines पर भी। यह CPython की memory management को simpler और thread-safe बनाने के लिए है।

import threading
import time

def cpu_bound_task():
    count = 0
    for i in range(50_000_000):
        count += 1
    return count

start = time.time()
t1 = threading.Thread(target=cpu_bound_task)
t2 = threading.Thread(target=cpu_bound_task)
t1.start(); t2.start()
t1.join(); t2.join()
print(f'Threaded: {time.time() - start:.2f}s')
# GIL के कारण multi-core पर दोगुना तेज़ नहीं होता

start = time.time()
cpu_bound_task()
cpu_bound_task()
print(f'Sequential: {time.time() - start:.2f}s')
# अक्सर threaded version के बराबर या बेहतर
Workload typeGIL का असर
CPU-boundThreads मदद नहीं करते
I/O-boundThreads मदद करते हैं - I/O wait में GIL release होता है

Was this answer clear?