多个进程之间的多处理同步(Python)

Multiprocessing synchronization between multiple processes (Python)

所以在大学实践中 class 是一个练习:

"Create program that defines shared value as 0, then creates and starts 500 processes, each of which increases value of shared value by 1, and finally in the end prints shared value. Run this code few times and see what happens, explain...."

最终版本看起来像:

from multiprocessing import Process, Value


n=Value('i', 0)

def fun():
        n.value+=1

for i in range(500):
        p=Process(target=fun).start()

print n.value

输出值在 420-480 范围内变化,我明白为什么。
问题是如果可能的话如何让它总是 500? 我一直在阅读 Python 文档并找到了可能的解决方案 - 信号量,但也许我不太了解它..
在 Semaphore 代码的情况下看起来:

from multiprocessing import Process, Value, Semaphore

n=Value('i', 0)
sem=Semaphore()

def fun():
        sem.acquire()
        n.value+=1
        sem.release()

for i in range(500):
    p=Process(target=fun).start()
print n.value

在这种情况下,最终输出在 492-495 范围内变化 - 更好。

P.S。不要建议我使用线程中的线程 class - 问题是关于多处理的。

您的进程未加入。因此,您的锁有效,但在完成所有递增过程之前显示 n 的值,因此 n<500。 您可以试试下面的代码:

from multiprocessing import Process, Value, Semaphore

n=Value('i', 0)
sem=Semaphore()

def fun():
        sem.acquire()
        n.value+=1
        sem.release()

pcs=[]
for i in range(500):
    p=Process(target=fun)
    pcs.append(p)
    p.start()
for i in pcs:
    i.join()
print n.value