-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathexample_6.py
More file actions
44 lines (32 loc) · 1.13 KB
/
example_6.py
File metadata and controls
44 lines (32 loc) · 1.13 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
import asyncio
import time
from concurrent.futures import ProcessPoolExecutor
def fetch_data(param):
print(f"Do something with {param}...", flush=True)
time.sleep(param)
print(f"Done with {param}", flush=True)
return f"Result of {param}"
async def main():
# Run in Threads
task1 = asyncio.create_task(asyncio.to_thread(fetch_data, 1))
task2 = asyncio.create_task(asyncio.to_thread(fetch_data, 2))
result1 = await task1
print("Thread 1 fully completed")
result2 = await task2
print("Thread 2 fully completed")
# Run in Process Pool
loop = asyncio.get_running_loop()
with ProcessPoolExecutor() as executor:
task1 = loop.run_in_executor(executor, fetch_data, 1)
task2 = loop.run_in_executor(executor, fetch_data, 2)
result1 = await task1
print("Process 1 fully completed")
result2 = await task2
print("Process 2 fully completed")
return [result1, result2]
if __name__ == "__main__":
t1 = time.perf_counter()
results = asyncio.run(main())
print(results)
t2 = time.perf_counter()
print(f"Finished in {t2 - t1:.2f} seconds")