Grade 10 Computer Science · Concurrency and time
When more than one thing happens
Why run in parallel at all, and what it breaks.
The same processor, and only downloads get faster
On a computer with just one processor, ten downloads started together finish much sooner than ten downloads one after another. But ten photos shrunk together finish no sooner at all. If both cases are called “running in parallel”, what is the difference between them?
Until now your program did one thing at each moment, in the order you wrote. That assumption hides two advantages achievable without it, and it is also what stood behind all the intuition you developed. The moment it is removed, part of what you knew about code stops being true.
# sequential: three calls, one after another
a = fetch("one"); b = fetch("two"); c = fetch("three")
# concurrent: three calls, all waiting together
import asyncio
a, b, c = await asyncio.gather(
fetch("one"), fetch("two"), fetch("three"),
)What breaks
The assumption that breaks is that lines run in order. When there are two sequences, each advances in its own order, but their interleaving is undefined: the system is free to stop one sequence midway and let the other run, and to do so at a different point on every run. As a result, exactly the same code can succeed a thousand times and fail on the thousand and first, with nothing having changed.
| The reason | Helps when | The tool |
|---|---|---|
| Waiting | Most of the time passes waiting | Calls running together |
| Computing | There are several processors | Splitting among processors |
Example 1 — why waiting is saved even on one processor
- The call is sent and the answer awaited.
- During the wait the processor is free.
- Another call can be sent.
Example 2 — why computing needs processors
- The work itself occupies a processor.
- Splitting on one processor saves nothing.
- Only several processors help.