gpt4 book ai didi

python并行循环: communicate to outside

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:46 25 4
gpt4 key购买 nike

我正在尝试运行一个并行循环(免责声明:我是并行处理的新手,这可能是一个非常愚蠢的问题)。本质上,我希望能够在并行函数中启动和终止循环,并且能够不时地检查其状态。

我尝试编写一个非常基本的示例(见下文),使用多处理进程和队列,其中子函数启动并开始循环。在每次迭代中,它都会向队列中添加一个值,因此它可以与外部进行通信。但是,我从队列中获得的值是我请求 queue.get() 的次数的结果。

运行代码,问题可能更有意义。非常感谢替代和更简单的方法。

import time
from multiprocessing import Process, Queue

def f(q):
z = 0
while True:
z = z+1
print 'z', z
q.put(['f is at z value {}'.format(z)])
time.sleep(float(0.1))

if __name__ == '__main__':
queue = Queue()
process = Process(target=f, args=(queue,))
process.start()
print 'start with z value:'
print queue.get()
time.sleep(1)

print 'now f is at z value:'
print queue.get()

time.sleep(1)
print 'terminating with z value:'
print queue.get()
process.terminate()

最佳答案

您可以使用 ArrayValuemultiprocessingshare the state进程之间:

import time
from multiprocessing import Process, Value

def f(v):
z = 0
while True:
z = z+1
print 'z', z
v.value = z
time.sleep(float(0.1))

if __name__ == '__main__':
value = Value('i')
value.value = -1
process = Process(target=f, args=(value,))
process.start()
print 'start with z value:'
print value.value
time.sleep(1)

print 'now f is at z value:'
print value.value

time.sleep(1)
print 'terminating with z value:'
print value.value
process.terminate()

输出:

start with z value:
-1
z 1
z 2
z 3
z 4
z 5
z 6
z 7
z 8
z 9
z 10
now f is at z value:
10
z 11
z 12
z 13
z 14
z 15
z 16
z 17
z 18
z 19
z 20
terminating with z value:
20

关于python并行循环: communicate to outside,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45942631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com