Log inStart free
LESSON 1.09 · 5 STAGES · 3 CONTROLS · 3 CHECKSPRO · PREVIEW

Threads and the GIL

Watch threads take turns with the GIL, and see which work gets faster.


Pro lesson. Stage 1 is free to watch. Pro opens all 5 stages, 3 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 1.09 · THREAD BAY2 THREADS · 1 PROCESS · 4 CORES
01
Stage 1 of 5 · Start threads
main starts 2 threads in one process. They share its memory and one GIL.
Explain it simply

A thread is one path through your code. Here main starts 2 threads and waits for them. T1 and T2 run CPU 1 and CPU 2, 40 ms of Python work each. They all share the memory of one process, like the done list.

Process 4728 holds main and 2 threads. T1 runs CPU 1 and T2 runs CPU 2.

runs bytecodeGIL and switch intervalwaits for the GILI/O wait, joinfinish, total time
process 4728memoryGIL1 holdermain4728T1CPU 14729T2CPU 24730done = []0 msGILcores busymax 1 of 401020304050607080msone after another80 msprocess 4728memoryGIL1 holdermain4728T1CPU 14729T2CPU 24730done = []0 msGILcores busymax 1 of 401020304050607080msone after another80 ms
Toy: the 1.C1 tasks · 2 or 4 threads · 4 cores · CPython's GIL rules · CPU n: 40 ms · I/O n: 5 ms + wait + 5 ms
STAGE 1 / 5
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
threads=N,processes=1,cores=4\text{threads} = \sy{n}{data}{N},\quad \text{processes} = 1,\quad \text{cores} = \sy{c}{param}{4}
N=2,pid=4728,thread ids=4729,4730N = 2,\quad \text{pid} = 4728,\quad \text{thread ids} = 4729, 4730

One process holds every thread, and all of them see one memory.

Common mix-ups

MYTHThreads make CPU-bound Python code faster.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01With 4 I/O-bound threads, does the run take about 103 ms or about 275 ms?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 5
Unlock the full explainer
  • 4 more stages and 3 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.