- async
- await
Async chores
examples/async/async_chores.py
import time import asyncio async def boil_water(sec): print(f"Start boiling water for {sec} seconds") await asyncio.sleep(sec) print(f"End boiling water for {sec} seconds") async def washing_machine(sec): print(f"Start washing machine for {sec} seconds") await asyncio.sleep(sec) print(f"End washing machine for {sec} seconds") await dryer(3) async def dryer(sec): print(f"Start dryer for {sec} seconds") await asyncio.sleep(sec) print(f"End dryer for {sec} seconds") async def dishwasher(sec): print(f"Start dishwasher for {sec} seconds") await asyncio.sleep(sec) print(f"End dishwasher for {sec} seconds") async def clean_potatoes(pieces): print(f"Start cleaning potatoes for {pieces} pieces") for ix in range(pieces): print(f"Cleaning potato {ix}") time.sleep(0.5) #await asyncio.sleep(0.0001) print(f"End cleaning potatoes for {pieces} pieces") async def main(): await asyncio.gather( dishwasher(3), washing_machine(3), boil_water(4), clean_potatoes(14)) start = time.time() asyncio.run(main()) end = time.time() print(f"Elapsed {end-start}")
From the output you can see that we noticed that the washing machine has finished only after we have finished all the potatoes. That's becasue our potato cleaning process was a long-running CPU-intensive process. This means the dryer only starts working after the potatoes are clean.
Start dishwasher for 3 seconds Start washing machine for 3 seconds Start boiling water for 4 seconds Start cleaning potatoes for 14 pieces Cleaning potato 0 Cleaning potato 1 Cleaning potato 2 Cleaning potato 3 Cleaning potato 4 Cleaning potato 5 Cleaning potato 6 Cleaning potato 7 Cleaning potato 8 Cleaning potato 9 Cleaning potato 10 Cleaning potato 11 Cleaning potato 12 Cleaning potato 13 End cleaning potatoes for 14 pieces End dishwasher for 3 seconds End washing machine for 3 seconds Start dryer for 3 seconds End boiling water for 4 seconds End dryer for 3 seconds Elapsed 10.01340126991272
If after cleaning each potato we look up for a fraction of a second, if we let the main loop run, then we can notice that the washing machine has ended and we can turn on the dryer before continuing with the next potato. This will allow the dryer to work while we are still cleaning the potatoes.
Start dishwasher for 3 seconds Start washing machine for 3 seconds Start boiling water for 4 seconds Start cleaning potatoes for 14 pieces Cleaning potato 0 Cleaning potato 1 Cleaning potato 2 Cleaning potato 3 Cleaning potato 4 Cleaning potato 5 End dishwasher for 3 seconds End washing machine for 3 seconds Start dryer for 3 seconds Cleaning potato 6 Cleaning potato 7 End boiling water for 4 seconds Cleaning potato 8 Cleaning potato 9 Cleaning potato 10 Cleaning potato 11 End dryer for 3 seconds Cleaning potato 12 Cleaning potato 13 End cleaning potatoes for 14 pieces Elapsed 7.02296781539917