【发布时间】:2017-07-19 00:50:11
【问题描述】:
考虑以下示例:
from multiprocessing import Queue, Pool
def work(*args):
print('work')
return 0
if __name__ == '__main__':
queue = Queue()
pool = Pool(1)
result = pool.apply_async(work, args=(queue,))
print(result.get())
这会引发以下RuntimeError:
Traceback (most recent call last):
File "/tmp/test.py", line 11, in <module>
print(result.get())
[...]
RuntimeError: Queue objects should only be shared between processes through inheritance
但有趣的是,只有当我尝试get 结果时才会引发异常,而不是在“共享”发生时。当我实际上确实共享队列时,注释相应的行会消除错误(并且永远不会执行work!)。
所以我的问题来了:为什么这个异常只在请求结果时引发,而不是在调用 apply_async 方法时引发,即使错误似乎被识别为目标 @ 987654332@函数从未被调用?
看起来异常发生在不同的进程中,只有在以请求结果的形式进行进程间通信时才能使主进程可用。但是,然后,我想知道为什么在调度到其他进程之前不执行此类检查。
(如果我在work 和主进程中都使用队列进行通信,那么这会(默默地)引入死锁。)
Python 版本是 3.5.2。
我已阅读以下问题:
- Sharing many queues among processes in Python
- How do you pass a Queue reference to a function managed by pool.map_async()?
- Sharing a result queue among several processes
- Python multiprocessing: RuntimeError: “Queue objects should only be shared between processes through inheritance”
- Python sharing a lock between processes
【问题讨论】:
标签: python python-3.x multiprocessing python-multiprocessing