-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasync-demo.py
More file actions
60 lines (45 loc) · 1.28 KB
/
async-demo.py
File metadata and controls
60 lines (45 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import asyncio
import time
async def make_coffee():
print("Making coffee")
# await asyncio.sleep(3)
print("Coffee is ready")
return "coffee"
async def make_toast():
print("Making toast")
await asyncio.sleep(2)
print("Toast is ready")
return "toast"
async def apply_butter():
print("Applying butter")
await asyncio.sleep(1)
print("Butter is applied")
return "toast with butter"
async def make_eggs():
print("Making eggs")
await asyncio.sleep(1)
print("Eggs are ready")
return "eggs"
async def main():
# coffee = await make_coffee() # --> Coroutine
# print(coffee)
# taost = await make_toast()
# print(taost)
# eggs = await make_eggs()
# coffee, toast, eggs = await asyncio.gather(
# make_coffee(), make_toast(), make_eggs(),
# )
# # print(await apply_butter())
# print(coffee, toast, eggs)
tasks = []
async with asyncio.TaskGroup() as tg:
tasks.append(tg.create_task(make_coffee()))
tasks.append(tg.create_task(make_eggs()))
tasks.append(tg.create_task(make_toast()))
for task in tasks:
print(task.result())
if __name__ == "__main__":
start = time.time()
asyncio.run(main())
end = time.time()
print(f"Time taken: {(end - start):2f}")