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
- Python
- Javascript
def counter(n):
total = 0
for i in range(n):
total += i
return total
counter(100) # Returns 0 to 100
function counter(n) {
let total = 0;
for(let i = 0; i < n; i++>){
total += i;
}
return total;
}
Coroutine Example
- Python
- Javascript
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())
async function doWork(name, delaySeconds) {
console.log(`${name}: start`);
await new Promise(resolve => setTimeout(resolve, delaySeconds * 1000)); // suspension point
console.log(`${name}: end after ${delaySeconds}s`);
}
async function main() {
const t0 = performance.now();
// Schedule three coroutines concurrently
await Promise.all([
doWork("A", 1),
doWork("B", 1),
doWork("C", 1)
]);
const elapsed = (performance.now() - t0) / 1000;
console.log(`elapsed ~${elapsed.toFixed(2)}s`);
}
main().catch(err => console.error(err));
- Python
- Javascript