Codele / Advanced programming
Async and await
A good waiter never stands at the kitchen door. When a table has to wait, the waiter sets it aside, serves another table, and comes back when the food is ready.
- A task is a job that may have to wait, for the network or a file. Async code lets a waiting task park so the single worker can do something else.
- The event loop is the routine in the story: take the next ready task, run it until it waits or ends, then repeat. Only one task runs at any moment.
- In real code, await marks the place where a task parks. Python writes async def and await (asyncio), JavaScript writes async and await, C# writes async Task and await. Java uses CompletableFuture and C++ uses std::async or futures. Go has no async/await: goroutines and channels do the same job.
- Async is not threads. With one worker there is nothing to lock, but a task that thinks hard without awaiting blocks everyone, so async shines for waiting jobs, not for heavy maths.
- This lesson simulates the loop with ticks so it prints the same everywhere. A real await waits for real time.
Loading the playable lesson…