多处理事件不起作用 [英] Multiprocessing Event not Working
问题描述
我已经使用多处理模块在Python 3中编写了以下代码.更多如何使用Event
是测试脚本.但是,它不起作用.
I have written the following code in Python 3 using the multiprocessing module. It's more of a test script to see how to use Event
. However, it's not working.
import multiprocessing, time
from multiprocessing import Process, Event
event = Event()
def f(n):
if n == 1:
print("starting")
event.wait()
print("Done!")
if n == 2:
time.sleep(3)
event.set()
print("setting")
if __name__ == "__main__":
p1 = Process(target = f, args = (1,))
p2 = Process(target = f, args = (2,))
p1.start()
p2.start()
time.sleep(1000)
但是,当我运行它时,我只会得到输出:
However, when I run this I only get the output:
starting
setting
我想获取输出:
starting
setting
Done!
但是由于某些原因,p2
进程调用了event.set()之后,p1
进程没有继续执行其代码.
But for some reason the p1
Process is not moving on with its code after event.set() has been called by the p2
process.
有任何想法为什么会发生这种情况?
Any ideas why this is happening?
推荐答案
From the multiprocessing
programming guidelines.
明确将资源传递给子进程
Explicitly pass resources to child processes
...最好将对象作为参数传递给子进程的构造函数.
... it is better to pass the object as an argument to the constructor for the child process.
除了使代码(可能)与Windows兼容...
Apart from making the code (potentially) compatible with Windows ...
在Windows上,您需要将共享对象传递到Process
构造函数的参数列表.否则,子进程将获得一个全新的副本,而不是父进程的副本.这就是f(1)
挂起,正在等待另一个Event
对象的原因.
On Windows, you need to pass the shared objects to the Process
constructor list of arguments. Otherwise, the child process will get a brand new copy instead of the parent's one. This is why f(1)
hangs, it is waiting on another Event
object.
只需更改这样的代码即可.
Just change the code like this.
def f(n, event):
if n == 1:
print("starting")
event.wait()
print("Done!")
elif n == 2:
time.sleep(3)
event.set()
print("setting")
if __name__ == "__main__":
event = Event() # one instance of Event only
p1 = Process(target = f, args = (1, event))
p2 = Process(target = f, args = (2, event))
p1.start()
p2.start()
p1.join()
p2.join()
这篇关于多处理事件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!