1 from multiprocessing import Pool,Queue。
其中Queue在Pool中不起作用,具体原因未明。
解决方案:
如果要用Pool创建进程,就需要使用multiprocessing.Manager()中的Queue,
与multiprocessing中的Queue不同
1
2
|
q = Manager().Queue() #Manager中的Queue才能配合Pool
po = Pool() # 无穷多进程
|
2 使用进程池,在进程中调用io读写操作。
例如:
1
2
3
4
|
p = Pool()
q = Manager().Queue()
with open ( '/home/cctv/data/stage_file/stage_{}.txt' . format ( int (time.time())), 'w' ) as w1:
p.apply_async(write_json, args = (video_path, 0 , 0.6 ,w1,q,i[ 0 ],))
|
这样也不会完成进程,只能把w放到具体的函数里面,不能通过参数调用
补充:python3进程池pool使用及注意事项
1.在python中使用进程池主要就是为了并行处理任务,缩短运行时间
2.经常使用方法: 同步有 apply(), map();异步的有 apply_async(), map_async()
3. 先看几个小例子
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
|
import time
from multiprocessing import Pool
test = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
def run(fn):
time.sleep( 1 )
return fn * fn
s = time.time()
for i in test:
run(i)
e = time.time()
print ( '直接循环 执行时间:' ,e - s)
pool = Pool( 8 )
s = time.time()
for i in test:
pool. apply (run, (i,))
e = time.time()
print ( 'apply 执行时间:' ,e - s)
pool1 = Pool( 8 )
s = time.time()
res = []
for i in test:
r = [pool1.apply_async(run, (i,))]
res.append(r)
pool1.close()
pool1.join()
e = time.time()
print ([i.get() for i in r])
print ( 'apply_async 执行时间:' ,e - s)
pool2 = Pool( 8 )
r = pool2. map (run,test)
pool2.close()
pool2.join()
e1 = time.time()
print (r)
print ( 'map执行时间:' ,e1 - e)
pool3 = Pool( 8 )
pool3.map_async(run,test)
pool3.close()
pool3.join()
e1 = time.time()
print ( 'map_async执行时间:' ,e1 - e)
|
执行结果
1
2
3
4
5
6
7
|
直接循环 执行时间: 8.004754781723022
apply 执行时间: 8.016774654388428
[ 64 ]
apply_async 执行时间: 1.1128439903259277
[ 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 ]
map 执行时间: 1.181443452835083
map_async执行时间: 2.3679864406585693
|
除此之外,在写代码中,还涉及到变量的一些问题。就需要加锁~
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/qq_41131535/article/details/89706178