解決Python 進(jìn)程池Pool中一些坑
其中Queue在Pool中不起作用,具體原因未明。
解決方案:如果要用Pool創(chuàng)建進(jìn)程,就需要使用multiprocessing.Manager()中的Queue,
與multiprocessing中的Queue不同
q=Manager().Queue()#Manager中的Queue才能配合Poolpo = Pool() # 無(wú)窮多進(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ù)里面,不能通過(guò)參數(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
除此之外,在寫代碼中,還涉及到變量的一些問(wèn)題。就需要加鎖~
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)2. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車輛管理系統(tǒng)3. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)4. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)5. Jsp servlet驗(yàn)證碼工具類分享6. jscript與vbscript 操作XML元素屬性的代碼7. 基于PHP做個(gè)圖片防盜鏈8. Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件列表展示(二)9. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解10. XML在語(yǔ)音合成中的應(yīng)用
