如何将队列引用传递给 pool.map_async() 管理的函数?
我想要一个长时间运行的进程通过队列(或类似的东西)返回其进度,我将其提供给进度栏对话框。当过程完成时我还需要结果。此处的测试示例失败,并出现 RuntimeError: Queue objects should only be Shared acrossprocesss through例如继承
。
import multiprocessing, time
def task(args):
count = args[0]
queue = args[1]
for i in xrange(count):
queue.put("%d mississippi" % i)
return "Done"
def main():
q = multiprocessing.Queue()
pool = multiprocessing.Pool()
result = pool.map_async(task, [(x, q) for x in range(10)])
time.sleep(1)
while not q.empty():
print q.get()
print result.get()
if __name__ == "__main__":
main()
我已经能够使用单独的 Process 对象(其中我am允许传递队列引用)来使其工作,但是我没有一个池来管理我想要启动的许多进程。关于更好的模式有什么建议吗?
I want a long-running process to return its progress over a Queue (or something similar) which I will feed to a progress bar dialog. I also need the result when the process is completed. A test example here fails with a RuntimeError: Queue objects should only be shared between processes through inheritance
.
import multiprocessing, time
def task(args):
count = args[0]
queue = args[1]
for i in xrange(count):
queue.put("%d mississippi" % i)
return "Done"
def main():
q = multiprocessing.Queue()
pool = multiprocessing.Pool()
result = pool.map_async(task, [(x, q) for x in range(10)])
time.sleep(1)
while not q.empty():
print q.get()
print result.get()
if __name__ == "__main__":
main()
I've been able to get this to work using individual Process objects (where I am alowed to pass a Queue reference) but then I don't have a pool to manage the many processes I want to launch. Any advise on a better pattern for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使
q
global 有效...:如果您需要多个队列,例如为了避免混淆各个池进程的进度,则应该使用全局队列列表(当然,每个进程都需要知道列表中要使用的索引,但这可以作为参数传递;-)。
Making
q
global works...:If you need multiple queues, e.g. to avoid mixing up the progress of the various pool processes, a global list of queues should work (of course, each process will then need to know what index in the list to use, but that's OK to pass as an argument;-).
以下代码似乎有效:
请注意,队列是从 manager.Queue() 而不是 multiprocessing.Queue() 获取的。感谢亚历克斯为我指明了这个方向。
The following code seems to work:
Note that the Queue is got from a manager.Queue() rather than multiprocessing.Queue(). Thanks Alex for pointing me in this direction.