- Designed for “cooperative/non-preemptive multitasking”
- Implements “parallelism” with only 1 thread
asnyc declares a “coroutine” (asynchronous function)
- Coroutines can be paused at some point to wait for an event without blocking other tasks in the same program
- Use the
await keyword in the function body to wait
- At every
await, the interpreter can switch to a different coroutine (if others are pending)
- At every
await, the compiler splits the function into 2 parts (before and after)
- Example: start a second task
task2 = asyncio.ensure_future(task2_fun())
- Starts
task2_fun() as a parallel task (and returns a handle)
- We need to await it before the end of
main such that the program doesn’t stop too early
await sec_task