2024-heraklion-parallel-python/extras/kitchen_asyncio/kitchen_asyncio_naive.py

76 lines
1.9 KiB
Python

import asyncio
import random
from kitchen_serial import parse_args
async def do_work(duration, result):
t = random.uniform(duration/5 * 0.5, duration/5 * 1.5)
await asyncio.sleep(t)
return result
async def fetch_olive_oil():
print('Fetching olive oil…')
return await do_work(5, 'oil')
async def fetch_dako_rusk():
print('Fetching dako rusk…')
return await do_work(5, 'rusk')
async def fetch_tomato():
print('Fetching tomato…')
return await do_work(3, 'tomato')
async def fetch_feta():
print('Fetching feta…')
return await do_work(3, 'feta')
async def chop_tomato(tomato):
assert tomato == 'tomato'
print('Chopping tomato…')
return await do_work(1, f'chopped {tomato}')
async def water_rusk(rusk):
assert rusk == 'rusk'
print('Watering rusk…')
return await do_work(0.2, f'wet {rusk}')
async def oil_rusk(rusk, oil):
assert rusk == 'wet rusk'
assert oil == 'oil'
print(f'Pouring {oil} on {rusk}')
return await do_work(0.5, f'{rusk} with {oil}')
async def decorate_rusk(rusk, *toppings):
result = rusk
for topping in toppings:
print(f'Putting {topping} on {result}')
result = await do_work(1, f'{result} with {topping}')
return result
async def store_dako(dako):
print(f'Storing {dako}')
await do_work(1, None)
async def prepare_dako():
print('Making dako…')
oil = await fetch_olive_oil()
rusk = await fetch_dako_rusk()
tomato = await fetch_tomato()
tomato = await chop_tomato(tomato)
rusk = await water_rusk(rusk)
rusk = await oil_rusk(rusk, oil)
feta = await fetch_feta()
dako = await decorate_rusk(rusk, tomato, feta)
await store_dako(dako)
print(f'{dako} is ready!')
async def prepare_dakos(n_dakos):
for n in range(args.n_dakos):
await prepare_dako()
if __name__ == '__main__':
args = parse_args()
asyncio.run(
prepare_dakos(args.n_dakos)
)