Python multiprocessing acync 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()

这样使用没有问题

赞 (0)

评论区

发表评论

暂无评论,要不来一发?

回到顶部