-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathexample_7.py
More file actions
43 lines (31 loc) · 1.17 KB
/
example_7.py
File metadata and controls
43 lines (31 loc) · 1.17 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
import asyncio
import time
async def fetch_data(param):
await asyncio.sleep(param)
return f"Result of {param}"
async def main():
# Create Tasks Manually
task1 = asyncio.create_task(fetch_data(1))
task2 = asyncio.create_task(fetch_data(2))
result1 = await task1
result2 = await task2
print(f"Task 1 and 2 awaited results: {[result1, result2]}")
# Gather Coroutines
coroutines = [fetch_data(i) for i in range(1, 3)]
results = await asyncio.gather(*coroutines, return_exceptions=True)
print(f"Coroutine Results: {results}")
# Gather Tasks
tasks = [asyncio.create_task(fetch_data(i)) for i in range(1, 3)]
results = await asyncio.gather(*tasks)
print(f"Task Results: {results}")
# Task Group
async with asyncio.TaskGroup() as tg:
results = [tg.create_task(fetch_data(i)) for i in range(1, 3)]
# All tasks are awaited when the context manager exits.
print(f"Task Group Results: {[result.result() for result in results]}")
return "Main Coroutine Done"
t1 = time.perf_counter()
results = asyncio.run(main())
print(results)
t2 = time.perf_counter()
print(f"Finished in {t2 - t1:.2f} seconds")