猿问

如何在多处理中使用锁作为互斥锁?

我想要两个过程,一个写入,一个读取/从同一变量读取。写入的数据如下所示:


[0, 0]

[0, 1]

[1, 0]

[1, 1]

[2, 0]

[2, 1]

[3, 0]

[3, 1]

[4, 0]

[4, 1]

[5, 0]

[5, 1]

[6, 0]

[6, 1]

[7, 0]

[7, 1]

[8, 0]

[8, 1]

[9, 0]

[9, 1]

但是我遇到了麻烦,因为读取过程是在变量变化之间读取,形成新的对,所以我想使用Lock/Mutex来防止这种情况再次发生。我想我必须在更改对象之前锁定它。OBS:使用管理器在进程之间共享对象。


下面是主代码:


import multiprocessing


def mde(dad, mutex):

    for i in range(10):

        for j in range(2):

            mutex.acquire()

            dad[0] = i

            dad[1] = j

            mutex.release()

def mda(dad):

    c = 0

    while c < 30:

        print(dad)

        c += 1


if __name__ == '__main__':

    manager = multiprocessing.Manager()

    mutex = manager.Lock()

    dado = manager.list([0, 0])

    p1 = multiprocessing.Process(target=mde, args=(dado, mutex,))

    p2 = multiprocessing.Process(target=mda, args=(dado,))

    p1.start()

    p2.start()

    p1.join()

    p2.join()

如您所见,我试图在编写过程中锁定和解锁变量,但结果仍然很混乱。我做错了什么?


扬帆大鱼
浏览 119回答 1
1回答

慕标5832272

这是更正后的版本(归功于宫城先生)。两个工人都在等待对方完成他们的任务,即修改列表或显示它。import multiprocessingNX = 10NY = 2def mde(dad, mutex):&nbsp; &nbsp; for i in range(NX):&nbsp; &nbsp; &nbsp; &nbsp; for j in range(NY):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mutex.acquire()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dad[0] = i&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dad[1] = j&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mutex.release()def mda(dad, mutex):&nbsp; &nbsp; c = 0&nbsp; &nbsp; while c <= NX*NY:&nbsp; &nbsp; &nbsp; &nbsp; mutex.acquire()&nbsp; &nbsp; &nbsp; &nbsp; print(dad)&nbsp; &nbsp; &nbsp; &nbsp; c += 1&nbsp; &nbsp; &nbsp; &nbsp; mutex.release()if __name__ == '__main__':&nbsp; &nbsp; manager = multiprocessing.Manager()&nbsp; &nbsp; mutex = manager.Lock()&nbsp; &nbsp; dado = manager.list([0, 0])&nbsp; &nbsp; p1 = multiprocessing.Process(target=mde, args=(dado, mutex,))&nbsp; &nbsp; p2 = multiprocessing.Process(target=mda, args=(dado, mutex,))&nbsp; &nbsp; p1.start()&nbsp; &nbsp; p2.start()&nbsp; &nbsp; p1.join()&nbsp; &nbsp; p2.join()
随时随地看视频慕课网APP

相关分类

Python
我要回答