Skip to content

Concurrency: Threads and the GIL

Beginning of the lesson

Concurrency: Threads and the GIL

Run overlapping work with threads, understand why the GIL limits them, and keep shared state correct with locks

Big Idea: A thread lets one Python process do several things that overlap in time. But CPython protects its internals with a single mutex called the Global Interpreter Lock (GIL): only one thread can execute Python bytecode at any instant. So threads give you real speedups for I/O-bound work (waiting on the network, disk or a database) but almost none for CPU-bound work. Whenever two threads touch the same mutable data you must serialise that access with a Lock, or you get race conditions.
By the end you will be able to:
  • distinguish concurrency from parallelism,
  • start and join threads with the threading module,
  • explain what the GIL guarantees and what it costs,
  • decide when threads help (I/O-bound) and when they do not (CPU-bound),
  • spot a race condition and fix it with a Lock or with lock:,
  • reach for ThreadPoolExecutor and queue.Queue instead of managing raw threads.

1. Concurrency is not the same as parallelism

Concurrency is a way of structuring a program so that several tasks are in progress at once — they can be interleaved on a single core, each making a little progress in turn. Parallelism is when tasks literally run at the same instant on multiple cores. Concurrency is about dealing with many things; parallelism is about doing many things simultaneously. Threads in CPython give you concurrency; because of the GIL they rarely give you parallelism for pure-Python CPU work.

This distinction is the key to the whole topic. Threads let a program wait on many things at once — twenty open sockets, ten files, five HTTP requests — so the total wall-clock time collapses toward the slowest single wait instead of the sum of all of them. What they cannot do is make one CPU-heavy Python loop finish faster.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers