如何更新进程中的 class 成员?
How can I update class members in processes?
我已经寻找了其他问题,this un-accepted-answered question 是我能找到的唯一一个以某种方式涵盖了这个问题并且没有真正帮助的问题。另外,我需要它来处理进程,而不是线程。
所以我从头开始写了一个示例程序来展示我的问题,你应该可以粘贴它,它会 运行:
import multiprocessing
import time
class Apple:
def __init__(self, color):
self.color = color
def thinkAboutApple(apple):
while True:
print(apple.color)
time.sleep(2)
my_apple = Apple("red")
new_process = multiprocessing.Process(target=thinkAboutApple, args=(my_apple,))
new_process.start()
time.sleep(4)
print("new: brown")
my_apple.color = "brown"
#so that the program doesn't exit after time.sleep(4)
while True:
pass
# actual output | # wanted output
red | red
red | red
new: brown | new: brown
red | brown
red | brown
这告诉我苹果处于一个奇怪的假设中,它同时是两种颜色,或者 new_process' 苹果在 ram 中处于另一个位置并且与 app 中的苹果分开主进程。
所以问题是:有没有办法让进程中的苹果指针指向同一个苹果,或者让所有进程中的苹果的所有实例保持相同的pythonic方法是什么?如果我在许多进程中有相同的苹果,甚至没有苹果的进程更多,我如何确保它们的面积始终相同?
您可以从(未记录的)multiprocessing.managers.NamespaceProxy
class 派生 Proxy
class 的专用版本,供 multiprocessing.BaseManager
使用,与基础版本不同class,公开其所有方法和属性。这类似于链接重复问题的@shtse8's answer,但我在这里发布了一个可运行的答案,以明确如何完成。
from multiprocessing import Process
from multiprocessing.managers import BaseManager, NamespaceProxy
import time
import types
class MyManager(BaseManager): pass # Avoid namespace pollution.
class Apple:
def __init__(self, color):
self.color = color
def Proxy(target):
""" Create a derived NamespaceProxy class for `target`. """
def __getattr__(self, key):
result = self._callmethod('__getattribute__', (key,))
if isinstance(result, types.MethodType):
def wrapper(*args, **kwargs):
self._callmethod(key, args)
return wrapper
return result
dic = {'types': types, '__getattr__': __getattr__}
proxy_name = target.__name__ + "Proxy"
ProxyType = type(proxy_name, (NamespaceProxy,), dic) # Create subclass.
ProxyType._exposed_ = tuple(dir(target))
return ProxyType
AppleProxy = Proxy(Apple)
def thinkAboutApple(apple):
while True:
print(f"apple.color: {apple.color}")
time.sleep(1)
if __name__ == '__main__':
MyManager.register('Apple', Apple, AppleProxy)
manager = MyManager()
manager.start()
my_apple = manager.Apple("red")
new_process = Process(target=thinkAboutApple, args=(my_apple,))
new_process.start()
time.sleep(2) # Allow other process to run a short while.
my_apple.color = "brown" # Change shared class instance.
time.sleep(2) # Allow other process to run at little while longer.
new_process.terminate()
我已经寻找了其他问题,this un-accepted-answered question 是我能找到的唯一一个以某种方式涵盖了这个问题并且没有真正帮助的问题。另外,我需要它来处理进程,而不是线程。
所以我从头开始写了一个示例程序来展示我的问题,你应该可以粘贴它,它会 运行:
import multiprocessing
import time
class Apple:
def __init__(self, color):
self.color = color
def thinkAboutApple(apple):
while True:
print(apple.color)
time.sleep(2)
my_apple = Apple("red")
new_process = multiprocessing.Process(target=thinkAboutApple, args=(my_apple,))
new_process.start()
time.sleep(4)
print("new: brown")
my_apple.color = "brown"
#so that the program doesn't exit after time.sleep(4)
while True:
pass
# actual output | # wanted output
red | red
red | red
new: brown | new: brown
red | brown
red | brown
这告诉我苹果处于一个奇怪的假设中,它同时是两种颜色,或者 new_process' 苹果在 ram 中处于另一个位置并且与 app 中的苹果分开主进程。
所以问题是:有没有办法让进程中的苹果指针指向同一个苹果,或者让所有进程中的苹果的所有实例保持相同的pythonic方法是什么?如果我在许多进程中有相同的苹果,甚至没有苹果的进程更多,我如何确保它们的面积始终相同?
您可以从(未记录的)multiprocessing.managers.NamespaceProxy
class 派生 Proxy
class 的专用版本,供 multiprocessing.BaseManager
使用,与基础版本不同class,公开其所有方法和属性。这类似于链接重复问题的@shtse8's answer,但我在这里发布了一个可运行的答案,以明确如何完成。
from multiprocessing import Process
from multiprocessing.managers import BaseManager, NamespaceProxy
import time
import types
class MyManager(BaseManager): pass # Avoid namespace pollution.
class Apple:
def __init__(self, color):
self.color = color
def Proxy(target):
""" Create a derived NamespaceProxy class for `target`. """
def __getattr__(self, key):
result = self._callmethod('__getattribute__', (key,))
if isinstance(result, types.MethodType):
def wrapper(*args, **kwargs):
self._callmethod(key, args)
return wrapper
return result
dic = {'types': types, '__getattr__': __getattr__}
proxy_name = target.__name__ + "Proxy"
ProxyType = type(proxy_name, (NamespaceProxy,), dic) # Create subclass.
ProxyType._exposed_ = tuple(dir(target))
return ProxyType
AppleProxy = Proxy(Apple)
def thinkAboutApple(apple):
while True:
print(f"apple.color: {apple.color}")
time.sleep(1)
if __name__ == '__main__':
MyManager.register('Apple', Apple, AppleProxy)
manager = MyManager()
manager.start()
my_apple = manager.Apple("red")
new_process = Process(target=thinkAboutApple, args=(my_apple,))
new_process.start()
time.sleep(2) # Allow other process to run a short while.
my_apple.color = "brown" # Change shared class instance.
time.sleep(2) # Allow other process to run at little while longer.
new_process.terminate()