多处理流程中的共享状态 [英] Shared state in multiprocessing Processes

查看:66
本文介绍了多处理流程中的共享状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

import time
from multiprocessing import Process

class Host(object):
    def __init__(self):
        self.id = None
    def callback(self):
        print "self.id = %s" % self.id
    def bind(self, event_source):
        event_source.callback = self.callback

class Event(object):
    def __init__(self):
        self.callback = None
    def trigger(self):
        self.callback()

h = Host()
h.id = "A"
e = Event()
h.bind(e)
e.trigger()

def delayed_trigger(f, delay):
    time.sleep(delay)
    f()

p = Process(target = delayed_trigger, args = (e.trigger, 3,))
p.start()

h.id = "B"
e.trigger()

这给出了输出

self.id = A
self.id = B
self.id = A

但是,我希望它能给

self.id = A
self.id = B
self.id = B

..因为在调用触发方法时h.id已更改为"B".

..because the h.id was already changed to "B" by the time the trigger method was called.

似乎在启动单独的Process时会创建主机实例的副本,因此原始主机中的更改不会影响该副本.

It seems that a copy of host instance is created at the moment when the separate Process is started, so the changes in the original host do not influence that copy.

在我的项目中(当然,要更详细地说明),主机实例字段有时会更改,并且由在单独的进程中运行的代码触发的事件具有访问这些更改的权限很重要.

In my project (more elaborate, of course), the host instance fields are altered time to time, and it is important that the events that are triggered by the code running in a separate process, have access to those changes.

推荐答案

多重处理在单独的进程中运行内容.事物在发送时被复制几乎是不可想象的,因为在进程之间共享内容需要共享内存或通信.

multiprocessing runs stuff in separate processes. It is almost inconceivable that things are not copied as they're sent, as sharing stuff between processes requires shared memory or communication.

实际上,如果您仔细阅读该模块,则可以通过

In fact, if you peruse the module, you can see the amount of effort it takes to actually share anything between the processes after the diverge, either through explicit communication, or through explicitly-shared objects (which are of a very limited subset of the language, and have to be managed by a Manager).

这篇关于多处理流程中的共享状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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