-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexecutor_example.py
51 lines (41 loc) · 1.36 KB
/
executor_example.py
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
"""
Show how to run blocking functions in a separate thread of process.
"""
import asyncio
import concurrent.futures as cf
import time
def long_running_function(n):
"""Sleep for n seconds."""
time.sleep(n)
def high_cpu_function(n):
"""Burn CPU cycles for n seconds."""
t0 = time.time()
i = 0
while time.time() - t0 < n:
i += 1
return i
if __name__ == '__main__':
loop = asyncio.get_event_loop()
# BAD!
# loop.run_until_complete(asyncio.wait([
# long_running_function(10),
# long_running_function(10),
# high_cpu_function(10),
# high_cpu_function(10),
# ]))
# Better
# executor = cf.ThreadPoolExecutor()
# loop.run_until_complete(asyncio.wait([
# loop.run_in_executor(executor, long_running_function, 10),
# loop.run_in_executor(executor, long_running_function, 10),
# loop.run_in_executor(executor, high_cpu_function, 10),
# loop.run_in_executor(executor, high_cpu_function, 10),
# ]))
# Best?
executor = cf.ProcessPoolExecutor()
loop.run_until_complete(asyncio.wait([
loop.run_in_executor(executor, long_running_function, 10),
loop.run_in_executor(executor, long_running_function, 10),
loop.run_in_executor(executor, high_cpu_function, 10),
loop.run_in_executor(executor, high_cpu_function, 10),
]))