下面发布的代码虽然不会崩溃,但不会从os.getpid()
函数返回foo
值。如何在多个队列对象上传递值,以便可以使用print(queue.get())
命令将其打印出来?
import time, multiprocessing, os
def foo(*args):
outside_queue = args[0]
logger = multiprocessing.log_to_stderr()
logger.warning(os.getpid())
outside_queue.put(os.getpid())
time.sleep(30)
class Object(object):
def run(self, *args):
outside_queue = args[0]
items = dict()
for i in range(5):
queue = multiprocessing.Queue()
proc = multiprocessing.Process(target=foo, args=(queue,))
items[proc] = queue
proc.start()
for proc, queue in items.items():
if not queue.empty():
outside_queue.put(queue.get())
for i in range(2):
obj = Object()
queue = multiprocessing.Queue()
proc = multiprocessing.Process(target=obj.run, args=(queue,))
proc.start()
while True:
proc.join(1)
if not proc.is_alive():
break
if not queue.empty():
print(queue.get())
time.sleep(0.1)
答案 0 :(得分:2)
这是一个同步问题,在Object.run
中,在启动子进程与从队列中获取结果之间,不能保证子进程已将某些内容放入队列中,您必须显式等待,使用{{ 1}},例如:
Event