使用多处理管理器在进程之间共享字节数组



我正在尝试在进程之间共享一个字节数组类型的变量。但是,我看不到multiprocessing.manager类中有字节数组类型。在进程之间共享字节数组变量的其他选项是什么?我知道我可以将它转换为字符串并将其传递给Manager.value("",""),但这不是一种有效的方法

我还没有专门研究过bytearray,所以可能还有另一种更有效的方法,但要创建一个所需数据类型的托管对象,只要它的属性都是可拾取的,就可以使用以下示例(只需将bytearray替换为要为其创建管理器的对象的类(:

from multiprocessing.managers import NamespaceProxy, BaseManager
import inspect

class ObjProxy(NamespaceProxy):
"""Returns a proxy instance for any user defined data-type. The proxy instance will have the namespace and
functions of the data-type (except private/protected callables/attributes). Furthermore, the proxy will be
pickable and can its state can be shared among different processes. """
@classmethod
def populate_obj_attributes(cls, real_cls):
DISALLOWED = set(dir(cls))
ALLOWED = ['__sizeof__', '__eq__', '__ne__', '__le__', '__repr__', '__dict__', '__lt__',
'__gt__']
DISALLOWED.add('__class__')
new_dict = {}
for (attr, value) in inspect.getmembers(real_cls, callable):
if attr not in DISALLOWED or attr in ALLOWED:
new_dict[attr] = cls._proxy_wrap(attr)
return new_dict
@staticmethod
def _proxy_wrap(attr):
""" This method creates function that calls the proxified object's method."""
def f(self, *args, **kwargs):
return self._callmethod(attr, args, kwargs)
return f
attributes = ObjProxy.populate_obj_attributes(bytearray)
bytearrayProxy = type("bytearrayProxy", (ObjProxy,), attributes)

if __name__ == "__main__":
BaseManager.register('bytearray', bytearray, bytearrayProxy, exposed=tuple(dir(bytearrayProxy)))
manager = BaseManager()
manager.start()

a = [2, 3, 4, 5, 7]
obj = manager.bytearray(a)
print(obj)

输出

bytearray(b'x02x03x04x05x07')

它通过复制所有公共属性和方法,为所需数据类型的对象(在本例中为bytearray(创建一个近乎完美的代理,包括特殊的dunder方法(如果类使用任何方法(。现在,您可以将obj传递给任何其他进程,存储在该对象中的数据将在所有进程中同步。

如果你想要更多关于这个代理如何工作的细节,我在这里写了一个详细的答案