Python multiprocessing 多程序鎖 程序間傳遞Lock 遇到的問題
阿新 • • 發佈:2018-12-13
無法傳遞 Lock物件
from multiprocessing import Pool,Lock
def text(i,lock):
print(i)
lock.acquire()
DOSOMETHING
lock.release()
if __name__ == '__main__':
lock=Lock()
pool=Pool(processes=8)
for i in range(1,1000):
pool.apply_async(text,(i,lock))
pool.close()
pool.join()
這裡的鎖是沒有作用的,一樣會衝突.因為lock不能作為物件傳參,所以增加Manager(日誌寫入鎖),其實是相當於一個專門的程序去處理Manager服務
from multiprocessing import Pool,Lock,Manager def text(i,lock): print(i) lock.acquire() temp=music_url.find({'singername':'v'})[0]['url']+1 music_url.update({'singername':'v'},{'$set':{'url':temp}}) lock.release() if __name__ == '__main__': arr=[] manager = Manager() lock=manager.Lock() pool=Pool(processes=8) for i in range(1,1000): pool.apply_async(text,(i,lock)) pool.close() pool.join() print(music_url.find({'singername':'v'})[0]['url'])
這樣改就完全沒有問題了