Python类继承多处理,访问类成员时遇到问题
简而言之,假设我有以下内容:
import multiprocessing
class Worker(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
print "Init"
self.value = None
def run(self):
print "Running"
self.value = 1
p = Worker()
p.start()
p.join()
print p.value
我希望输出为:
Init
Running
1
相反,
Init
Running
None
有人可以向我解释为什么会出现这种情况吗?我不明白什么,我应该如何正确地做?
谢谢。
In short, say I have the following:
import multiprocessing
class Worker(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
print "Init"
self.value = None
def run(self):
print "Running"
self.value = 1
p = Worker()
p.start()
p.join()
print p.value
I'd expect the output to be:
Init
Running
1
Instead it is
Init
Running
None
Can someone explain to me why this is the case? What am I not understanding, and how should I go about doing it correctly?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你说
p.start()
时,一个单独的进程就会从主进程中分叉出来。所有变量值都被复制。因此,主进程有一份p
副本,而分叉进程则有一份单独的p
副本。Worker
修改了分叉进程的p.value
副本,但主进程的p.value
仍然是None
。有很多方法可以在进程之间共享对象。在这种情况下,也许最简单的方法是使用 mp.Value:
请注意,
mp.Value
的默认值为0.0
。它不能设置为None
。The moment you say
p.start()
, a separate process is forked off of the main process. All variable values are copied. So the main process has one copy ofp
, and the forked process has a separate copy ofp
. TheWorker
modifies the forked process's copy ofp.value
, but the main process'sp.value
still isNone
.There are many ways to share objects between processes. In this case, perhaps the easiest way is to use a mp.Value:
Note that the
mp.Value
has a default value of0.0
. It can not be set toNone
.