gpt4 book ai didi

python - 如何更新进程中的类成员?

转载 作者:行者123 更新时间:2023-12-03 23:01:28 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Accessing an attribute of a multiprocessing Proxy of a class

(6 个回答)


10 个月前关闭。




我已经寻找其他问题,和 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 中的另一个位置,并与主进程中的苹果分开。
所以问题是:有没有办法让进程中苹果的指针指向同一个苹果,或者让所有进程中苹果的所有实例保持相同的pythonic方法是什么?如果我在许多过程中有相同的苹果,甚至没有苹果的更多过程中,我如何确保它们的面积始终相同?

最佳答案

您可以派生出 Proxy 的专用版本。 multiprocessing.BaseManager 使用的类来自(未记录的)multiprocessing.managers.NamespaceProxy与基类不同,它公开了它的所有方法和属性。这类似于 @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()

关于python - 如何更新进程中的类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65451457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com