【问题标题】:Sharing Boolean between processes在进程之间共享布尔值
【发布时间】:2019-06-11 18:43:39
【问题描述】:

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

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

另外,这是我的代码:

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

#queue gets written to...

bool_val = Value(“i”, 1)

#other thread
If bool(bool_val) is True:
    #read from queue

【问题讨论】:

  • 请向我们展示您尝试过的代码。这样就更容易说出还需要什么。
  • 添加到问题
  • 是的,您确实需要将bool_val 传递给您正在并行处理的函数

标签: python multithreading sockets audio multiprocessing


【解决方案1】:

如果您依赖使用 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

【讨论】:

    猜你喜欢
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2012-04-09
    • 2011-07-06
    • 2014-10-22
    相关资源
    最近更新 更多