【发布时间】:2021-07-17 12:03:59
【问题描述】:
我想在一个新进程中在 python 中运行一个函数,做一些工作,使用队列将进度返回到主进程并等待主进程终止生成的进程,然后继续执行主进程。
我得到以下代码,它在新进程中运行函数 foo 并使用队列返回进度:
import multiprocessing as mp
import time
def foo(queue):
for i in range(10):
queue.put(i)
time.sleep(1)
if __name__ == '__main__':
mp.set_start_method('spawn')
queue = mp.Queue()
p = mp.Process(target=foo, args=(queue,))
p.start()
while p.is_alive():
print("ALIVE")
print(queue.get())
time.sleep(0.01)
print("Process finished")
输出是:
ALIVE
0
ALIVE
1
ALIVE
2
ALIVE
3
ALIVE
4
ALIVE
5
ALIVE
6
ALIVE
7
ALIVE
8
ALIVE
9
ALIVE
在某些时候,“Alive”和“Process finished”都不会被打印出来。生成的进程停止运行时如何继续执行?
*编辑
问题是如果队列为空,我不知道 queue.get() 会阻塞,直到将一个项目放入队列。我通过更改来修复它
while p.is_alive():
print(queue.get())
time.sleep(0.01)
到
while p.is_alive():
if not queue.empty():
print(queue.get())
time.sleep(0.01)
【问题讨论】:
标签: python python-3.x multiprocessing python-multithreading