-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool_of_workers.py
More file actions
53 lines (46 loc) · 1.31 KB
/
pool_of_workers.py
File metadata and controls
53 lines (46 loc) · 1.31 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
from multiprocessing import Pool, TimeoutError
import time
import os
# http://www.cnblogs.com/resn/p/5591419.html
def myFun(i):
time.sleep(1)
# print(i + 100)
return i + 100
def end_call(arg):
print('end_call', arg)
if __name__ == '__main__':
p = Pool(5)
for i in range(10):
# p.apply(func=myFun, args=(i,)) # 一个一个执行
p.apply_async(func=myFun, args=(i,), callback=end_call) # 并发执行
print('end')
p.close()
p.join()
# def f(x):
# return x*x
#
# if __name__ == '__main__':
# with Pool(processes=4) as pool:
# print(pool.map(f, range(10)))
#
# for i in pool.imap_unordered(f, range(10)):
# print(i)
#
# res = pool.apply_async(f, (20,))
# print(res.get(timeout=1))
#
# res = pool.apply_async(os.getpid)
# print(res.get(timeout=1))
#
# multiple_results = [pool.apply_async(os.getpid) for i in range(4)]
# print([res.get(timeout=1) for res in multiple_results])
#
# res = pool.apply_async(time.sleep, (5,))
# try:
# print(res.get(timeout=1))
# except TimeoutError:
# print('发现一个 multiprocessing.TimeoutError异常')
#
# print('目前池中还有其他的工作')
#
# print('Now the pool is closed and no longer available')