Skip to main content

Asynchronous operations in Python.

Subroutine and coroutine

Subroutine

Top-down and stack based control flow such as a regular function that runs from start to finish. The caller blocks blocks until it returns.

Coroutine

A generalization of subroutine that can suspend at certain points and resume later, receiving a value back when resumed. Modern coroutine are created with async in python, and paused/resumed with await. This enables cooperative concurrancy.

Subroutine Example

def counter(n):
total = 0
for i in range(n):
total += i
return total

counter(100) # Returns 0 to 100

Coroutine Example

import asyncio
import time

async def do_work(name, delay):
print(f"{name}: start")
await asyncio.sleep(delay) # suspension point: lets other tasks run
print(f"{name}: end after {delay}s")

async def main():
t0 = time.perf_counter()
# Schedule three coroutines concurrently
await asyncio.gather(
do_work("A", 1),
do_work("B", 1),
do_work("C", 1),
)
print(f"elapsed ~{time.perf_counter() - t0:.2f}s")

asyncio.run(main())