解決Python 進(jìn)程池Pool中一些坑
其中Queue在Pool中不起作用,具體原因未明。
解決方案:如果要用Pool創(chuàng)建進(jìn)程,就需要使用multiprocessing.Manager()中的Queue,
與multiprocessing中的Queue不同
q=Manager().Queue()#Manager中的Queue才能配合Poolpo = Pool() # 無窮多進(jìn)程2 使用進(jìn)程池,在進(jìn)程中調(diào)用io讀寫操作。例如:
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],))
這樣也不會(huì)完成進(jìn)程,只能把w放到具體的函數(shù)里面,不能通過參數(shù)調(diào)用
補(bǔ)充:python3進(jìn)程池pool使用及注意事項(xiàng)
1.在python中使用進(jìn)程池主要就是為了并行處理任務(wù),縮短運(yùn)行時(shí)間
2.經(jīng)常使用方法: 同步有 apply(), map();異步的有 apply_async(), map_async()
3. 先看幾個(gè)小例子
import time from multiprocessing import Pool test = [1,2,3,4,5,6,7,8]def run(fn): time.sleep(1) return fn*fns = time.time()for i in test: run(i)e = time.time()print(’直接循環(huán) 執(zhí)行時(shí)間:’,e - s)pool = Pool(8)s = time.time()for i in test: pool.apply(run, (i,))e = time.time()print(’apply 執(zhí)行時(shí)間:’,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 執(zhí)行時(shí)間:’,e - s) pool2 = Pool(8)r = pool2.map(run,test)pool2.close()pool2.join() e1 = time.time()print(r)print(’map執(zhí)行時(shí)間:’,e1 - e)pool3 = Pool(8)pool3.map_async(run,test)pool3.close()pool3.join() e1 = time.time()print(’map_async執(zhí)行時(shí)間:’,e1 - e)
執(zhí)行結(jié)果
直接循環(huán) 執(zhí)行時(shí)間: 8.004754781723022apply 執(zhí)行時(shí)間: 8.016774654388428[64]apply_async 執(zhí)行時(shí)間: 1.1128439903259277[1, 4, 9, 16, 25, 36, 49, 64]map執(zhí)行時(shí)間: 1.181443452835083map_async執(zhí)行時(shí)間: 2.3679864406585693
除此之外,在寫代碼中,還涉及到變量的一些問題。就需要加鎖~
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. HTML DOM setInterval和clearInterval方法案例詳解2. jscript與vbscript 操作XML元素屬性的代碼3. XML在語音合成中的應(yīng)用4. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)5. Vue如何使用ElementUI對表單元素進(jìn)行自定義校驗(yàn)及踩坑6. XML入門的常見問題(三)7. 不要在HTML中濫用div8. XML 非法字符(轉(zhuǎn)義字符)9. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))10. CSS清除浮動(dòng)方法匯總
