下面发布的代码虽然没有崩溃,但不会从foo
函数返回os.getpid()
值。如何在多个队列对象上传递一个值,以便使用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)
这是一个同步问题,在Object.run
中,在启动子进程和从队列中获得结果之间,不能保证子进程已经向队列中放入了一些东西,您必须明确等待,使用Event
,例如:
def foo(outside_queue, evt):
outside_queue.put(os.getpid())
evt.set()
class Object(object):
def run(self, *args):
outside_queue = args[0]
items = dict()
for i in range(5):
evt = multiprocessing.Event()
queue = multiprocessing.Queue()
proc = multiprocessing.Process(target=foo, args=(queue, evt))
items[proc] = queue
proc.start()
evt.wait(None)
...