简体   繁体   English

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

[英]Multiprocessing synchronization between multiple processes (Python)

So there in college practical class was an exercise: 因此在大学实践课上是一个练习:

"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...." “创建一个将共享值定义为0的程序,然后创建并启动500个进程,每个进程将共享值的值增加1,最后最后打印共享值。运行此代码几次,看看会发生什么,解释。” ..”

Final version looks like: 最终版本如下:

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

Output value varies in range 420-480 and i understand why. 输出值在420-480范围内变化,我理解原因。
The questions is how to make it always 500 if it possible? 问题是,如果可能的话,如何使其始终为500? I've been reading Python docs and have found possible solution - Semaphore, but maybe I didn't understand it well.. 我一直在阅读Python文档,并找到了可能的解决方案-信号量,但也许我不太了解。
In the case of Semaphore code looks: 就信号量代码而言:

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

In this case the final output varies in range 492-495 - way better. 在这种情况下,最终输出在492-495范围内变化-更好。

PS Do not advise me to use threads from threading class - question is about multiprocessing. PS不要建议我使用线程类中的线程-问题是有关多处理的。

Your processes are not joined. 您的流程未加入。 Your lock therefore works, but the value of n is displayed before all of the processes are done to increment it, hence n<500. 因此,您的锁起作用了,但是在完成所有过程以增加n之前显示n的值,因此n <500。 You can try the following code: 您可以尝试以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM