在进程之间共享布尔值

时间:2019-06-11 18:43:39

标签: python multithreading sockets audio multiprocessing

我希望在Python的两个进程之间共享布尔值。我有一个队列,希望通过在while循环的第一次运行中填充它来初始化。此后,布尔值设置为true,其他进程现在可以开始从队列中读取了。

注意:我尝试使用值,但布尔值不会更新。我是否需要将布尔值作为arg传递给流程,才能使其正常工作?

另外,这是我的代码:

order
#Main thread
bool_val = Value(“i”, 0)

#queue gets written to...

bool_val = Value(“i”, 1)

1 个答案:

答案 0 :(得分:0)

如果您依赖使用multiprocessing.Value-可以通过value属性访问该对象本身。

这是一个原始示例:

from multiprocessing import Process, Value, Queue, cpu_count, current_process


def handle(v):
    val = v.value
    if bool(val) is True:
        print('process {} is using value {}'.format(current_process().name, val))
    else:
        v.value = 1
        print('process {} changed value {} to {}'
              .format(current_process().name, val, v.value))


if __name__ == '__main__':
    v = Value('i', 0)

    processes = [Process(target=handle, args=(v,)) for _ in range(cpu_count())]
    for p in processes:
        p.start()

    for p in processes:
        p.join()

    print(v, v.value)

输出:

process Process-1 changed value 0 to 1
process Process-2 is using value 1
process Process-3 is using value 1
process Process-4 is using value 1
process Process-5 is using value 1
process Process-6 is using value 1
process Process-7 is using value 1
process Process-8 is using value 1
process Process-9 is using value 1
process Process-10 is using value 1
process Process-11 is using value 1
process Process-12 is using value 1
<Synchronized wrapper for c_int(1)> 1