問題描述
請考慮以下代碼:
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.
似乎在啟動單獨進程的那一刻創建了主機實例的副本,因此原始主機中的更改不會影響該副本.
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.
事實上,如果您仔細閱讀該模塊,您可以通過 顯式通信,或通過 顯式共享對象(屬于非常有限的語言子集,必須由 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
).
這篇關于多處理進程中的共享狀態的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!