Python 分享价值

Python share values

在我的项目中,我有多个这样的标志:

file_a = False
file_b = False
file_c = False

我正在尝试 运行 两个进程:一个(从现在起称为 A)处理消息队列中的传入消息,第二个(从现在起称为 B)处理一些数据处理。 B 对布尔标志进行操作,A 设置其值:

def a():
    while True:
        ...
        ...
        file_a = True
        ...

def b():
    while True:
        ...
        if file_a:
            process(file_a)
            ...

a_proc = Process(target=a)
b_proc = Process(target=b)
a_proc.start()
b.proc.start()

但是,这些值似乎没有改变。我读到我应该使用线程,它似乎可以工作,但我的指导方针是使用多处理而不是线程。

如果需要用multiprocessing模块在进程间交换数据,可以直接共享内存:

multiprocessing.Value

Value 是 ctypes 对象的包装器,它具有表示内存中实际对象的基础 value 属性。 Value 所做的只是确保只有一个进程或线程可以同时读取或写入此值属性。

from multiprocessing import Value
file_a = Value('i', 0)
file_b = Value('i', 0)
file_c = Value('i', 1)

这将为您的文件标志创建共享整数值。既然是python,整数值和布尔值的转换就很简单:

>>> Value('i', True)
<Synchronized wrapper for c_int(1)>
>>> Value('i', False)
<Synchronized wrapper for c_int(0)>
>>> bool(Value('i', False).value)
False
>>> bool(Value('i', 50).value)
True

口味偏好,但也许更好的选择,您可以使用 c_bool from ctypes:

from multiprocessing import Value
from ctypes import c_bool
file_a = Value(c_bool, False)
file_n = Value(c_bool, False)
file_c = Value(c_bool, True)

>>> Value(c_bool, False)
<Synchronized wrapper for c_bool(False)>
>>> Value(c_bool, 5)
<Synchronized wrapper for c_bool(True)>

multiprocessing.Manager字典:

要收集多个布尔标志,您可以使用字典,但它需要在进程之间共享,因此 Manager() 派上用场。

from multiprocessing import Manager
manager = Manager()
flags = manager.dict({'file_a' : False, 'file_b' : False, 'file_c' : True})

>>> flags
<DictProxy object, typeid 'dict' at 0x7f70822f06d0>
>>> flags['file_a']
False
>>> dict(flags)
{'file_a': False, 'file_c': True, 'file_b': False}

最后把它们全部收集起来:

我会采用 Manager 方法,因为它会使代码更清晰:

from multiprocessing import Process, Manager
manager = Manager()

    def a():
        while True:
            ...
            ...
            flags['file_a'] = True
            ...

    def b():
        while True:
            ...
            if flags['file_a']:
                process(file_a)
                ...

    if __name__ == '__main__':
        flags = manager.dict({'file_a' : False, 'file_b' : False, 'file_c' : True})
        a_proc = Process(target=a)
        b_proc = Process(target=b)
        a_proc.start()
        b.proc.start()

您的 file_a, file_b, file_c 正在分别加载到每个进程中。您需要使用 multiprocessing

中的 Value