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()

这样使用没有问题

最后修改:2022 年 04 月 09 日
如果觉得我的文章对你有用,请随意赞赏