繁体   English   中英

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

[英]Sharing bytearray between processes with multiprocessing manager

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

我没有专门研究过bytearray ,所以也许还有另一种更有效的方法,但是要创建一个你想要的任何数据类型的托管 object,只要它的属性都是可挑选的,你可以按照这个示例(只需将bytearray替换为class 谁是 object 您要为其创建经理):

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)

Output

bytearray(b'\x02\x03\x04\x05\x07')

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

如果您想了解有关此代理如何工作的更多详细信息,我在这里写了一个详细的答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM