Python类继承多处理,访问类成员时遇到麻烦 [英] Python class inheriting multiprocessing, trouble with accessing class members

查看:74
本文介绍了Python类继承多处理,访问类成员时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,说我有以下内容:

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

我希望输出为:

Init
Running
1

相反,是

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?

谢谢.

推荐答案

您说出p.start()的那一刻,一个单独的过程即从主过程中分叉出来.复制所有变量值.因此,主进程具有一个p副本,而分支进程具有一个单独的p副本. Worker修改了分叉进程的p.value副本,但是主进程的p.value仍然是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 of p, and the forked process has a separate copy of p. The Worker modifies the forked process's copy of p.value, but the main process's p.value still is None.

有很多方法可以在进程之间共享对象.在这种情况下,也许最简单的方法是使用 mp.Value :

There are many ways to share objects between processes. In this case, perhaps the easiest way is to use a mp.Value:

import multiprocessing as mp

class Worker(mp.Process):
    def __init__(self):
        print "Init"
        mp.Process.__init__(self)
        self.num = mp.Value('d', 0.0)

    def run(self):
        print "Running"
        self.num.value = 1

p = Worker()
p.start()
p.join()
print p.num.value

请注意,mp.Value的默认值为0.0.不能将其设置为None.

Note that the mp.Value has a default value of 0.0. It can not be set to None.

这篇关于Python类继承多处理,访问类成员时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆