Bitpath

Lesson 2 · Unit 04

The GIL

Threads for waiting, processes for computing, asyncio between

13 exercisesabout 3 min

What you practise

  • The global interpreter lock and what it serialises, threads for waiting and processes for computing, where asyncio fits
  • 13 has the general theory

Try a question from this lesson

Pick one

A pure-Python counting loop takes 2 s. On a four-core machine with the default CPython build, two threads each run that loop. About how long until both finish?

Hint

Count how many threads can be executing Python bytecode at any one instant.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The global interpreter lock

The default CPython build has a global interpreter lock (GIL): only one thread executes Python bytecode at a time. Threads take turns, so extra threads do not speed up pure-Python computation.

A thread lets the GIL go while it waits on the network, a file or a sleep. That is why threads still help with I/O.

A free-threaded build of CPython without the GIL also exists. It is a separate build: unless you chose it, assume the GIL.

Concept

Where asyncio fits

asyncio runs many tasks in one thread. A task runs until it reaches an await, and only there can the event loop switch to another task.

So waiting is cheap: thousands of tasks can be parked at an await. But a task that computes without awaiting blocks every other task, and nothing runs in parallel.

Python
import asyncio

async def fetch(n):
    await asyncio.sleep(0)   # a wait
    return n * 10

async def main():
    both = asyncio.gather(fetch(1),
                          fetch(2))
    print(await both)        # [10, 20]

asyncio.run(main())

10 more exercises in the app

  • 3× multiple choice
  • 4× type the answer
  • 1× fill the blanks
  • 1× match the pairs
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy