CodeBlanks Logo Icon CodeBlanks

GIL

Learn the GIL (Global Interpreter Lock) concept.

What is the GIL?

The GIL (Global Interpreter Lock) is a lock in CPython that ensures only one thread executes Python bytecode at a time. This means threading does not speed up CPU-bound work.

For I/O-bound work (network, files) the GIL is released; so threading is still useful there. But for pure computation threads run sequentially; there is no parallelism. To parallelize CPU-bound work you use multiprocessing; each process has its own GIL.

Effect of the GIL

The GIL is not a problem for I/O-bound work. When a thread does time.sleep() or a network request it releases the GIL; other threads can run.

But a CPU-bound loop (such as for i in range(1000000): pass) holds the GIL continuously. Other threads wait during this time. So two CPU-bound threads run as fast as a single thread; there is no parallelism gain. If you need true parallel CPU power multiprocessing is the only option.

Practice CPU-bound work under the GIL

Import with from threading import Thread. Define a count function that increments total in a for i in range(1000): loop and does print("bitti"). Create a thread with Thread(target=count), call .start() and .join().

Starter code

main.py
# write the count function
# create and run a thread

Sample solution

main.py
from threading import Thread

def count():
    total = 0
    for i in range(1000):
        total += 1
    print("done")

t = Thread(target=count)
t.start()
t.join()

Expected output

bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the GIL abbreviation

Question
GIL: Global ____ Lock
Answer
GIL: Global Interpreter Lock

Explanation: GIL = Global Interpreter Lock.

2 Match GIL concepts

Term Meaning
GIL Global Interpreter Lock
CPU-bound No parallelism
I/O-bound GIL released
multiprocessing Own GIL

3 What is used to parallelize CPU-bound work?

  • threading
  • Lock
  • multiprocessing Correct answer
  • asyncio

Explanation: multiprocessing gives each process its own GIL; CPU work parallelizes.

All lessons in Expert