Joh*_*ook 0 python sockets audio multithreading multiprocessing
I\xe2\x80\x99m 希望在 Python 中的两个进程之间共享 bool 值。我有一个队列,我想通过让它在第一次运行 while 循环时填满来初始化。此后,布尔值设置为 true,其他进程现在可以开始从队列中读取。
\n\n注意:我\xe2\x80\x99已经尝试使用值,但布尔不会\xe2\x80\x99t更新。我是否需要将 bool 作为参数传递给进程才能使其工作?
\n\n另外,这是我的代码:
\n\n#Main thread\nbool_val = Value(\xe2\x80\x9ci\xe2\x80\x9d, 0)\n\n#queue gets written to...\n\nbool_val = Value(\xe2\x80\x9ci\xe2\x80\x9d, 1)\n\nRun Code Online (Sandbox Code Playgroud)\n\n#other thread\nIf bool(bool_val) is True:\n #read from queue\nRun Code Online (Sandbox Code Playgroud)\n
如果您依赖于使用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)
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4635 次 |
| 最近记录: |