Log inStart free
LESSON 1.C1 · 5 STAGES · 2 CONTROLS · 3 CHECKSPRO · PREVIEW

Python concurrency — threads vs processes vs asyncio

Watch 8 tasks run four ways on one timeline, and see which finishes first.


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

Go Pro · $8.25/mo
EXPLAINER · 1.C1 · CONCURRENCY BAYONE AFTER ANOTHER · 435 MS · 1.0× · MAX 1 CORE
01
Stage 1 of 5 · Baseline
One thread runs the tasks in turn. While an I/O-bound task waits, the CPU sits idle.
Explain it simply

Eight tasks wait to run. The I/O-bound ones mostly wait, like a download. The CPU-bound ones only compute. One thread runs them in order. Look at the strip at the top: while a task waits, it drops to zero. The CPU sits idle.

One thread runs the 8 tasks one after another. 200 ms of Python work plus 235 ms of waits end at 435 ms.

Python workI/O waitblocked by the GIL or loopprocess start, data copy, switch intervaldone
tasks1 thread · 1 task at a timems0100200300400coresbusy41max 1 coreI/O 1mainI/O 2mainI/O 3mainI/O 4mainCPU 1mainCPU 2mainCPU 3mainCPU 4main51436378T = 435 ms61114187275315355395435T = 200 Python + 235 wait = 435 mstasks1 thread · 1 task at a timems0100200300400coresbusy41max 1 coreI/O 1mainI/O 2mainI/O 3mainI/O 4mainCPU 1mainCPU 2mainCPU 3mainCPU 4main51436378T = 435 ms61114187275315355395435T = 200 Python + 235 wait = 435 ms
Toy: 4 cores · 8 tasks · 1 ms steps · costs measured on CPython 3.12, rounded
STAGE 1 / 5
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
T=∑Python+∑wait\sy{T}{out}{T} = \sum \sy{cpu}{data}{\text{Python}} + \sum \sy{io}{ink}{\text{wait}}
T=200+235=435 msT = 200 + 235 = \sy{T}{out}{435}\ \text{ms}

One after another, the total is all work plus all waits.

Common mix-ups

MYTHMore threads make CPU-bound Python faster.

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

Predict, then reveal
3 CHECKS · PRO
Q01With 8 CPU-bound tasks, which runner finishes first?

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 2 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.