問(wèn)題描述
請(qǐng)考慮以下代碼:
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
..因?yàn)樵谡{(diào)用觸發(fā)方法時(shí),h.id 已經(jīng)更改為B".
..because the h.id was already changed to "B" by the time the trigger method was called.
似乎在啟動(dòng)單獨(dú)進(jìn)程的那一刻創(chuàng)建了主機(jī)實(shí)例的副本,因此原始主機(jī)中的更改不會(huì)影響該副本.
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.
在我的項(xiàng)目中(當(dāng)然更詳細(xì)),主機(jī)實(shí)例字段會(huì)不時(shí)更改,重要的是由在單獨(dú)進(jìn)程中運(yùn)行的代碼觸發(fā)的事件能夠訪問(wèn)這些更改.
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.
推薦答案
多處理 在單獨(dú)的進(jìn)程中運(yùn)行東西.在發(fā)送時(shí)不復(fù)制內(nèi)容幾乎是不可想象的,因?yàn)樵谶M(jìn)程之間共享內(nèi)容需要共享內(nèi)存或通信.
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.
事實(shí)上,如果您仔細(xì)閱讀該模塊,您可以通過(guò) 顯式通信,或通過(guò) 顯式共享對(duì)象(屬于非常有限的語(yǔ)言子集,必須由 Manager代碼>).
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
).
這篇關(guān)于多處理進(jìn)程中的共享狀態(tài)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!