Python multiprocessing 多进程锁 进程间传递Lock 遇到的问题

无法传递 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'])

这样改就完全没有问题了

你可能感兴趣的:(python,python,multiprocessing,pool,lock,进程锁)