問題描述
我想要一個長時間運行的進程通過隊列(或類似的東西)返回它的進度,我將把它提供給進度條對話框.當過程完成時,我還需要結果.此處的測試示例失敗并出現 RuntimeError: Queue objects should only be shared between processes through inheritance
.
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()
我已經能夠使用單獨的 Process 對象(我 am 允許傳遞 Queue 引用)使其工作,但是我沒有一個池來管理我的許多進程想啟動.有什么更好的模式建議嗎?
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?
推薦答案
以下代碼似乎可以工作:
The following code seems to work:
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():
manager = multiprocessing.Manager()
q = manager.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()
請注意,隊列來自 manager.Queue() 而不是 multiprocessing.Queue().感謝 Alex 為我指明了這個方向.
Note that the Queue is got from a manager.Queue() rather than multiprocessing.Queue(). Thanks Alex for pointing me in this direction.
這篇關于如何將隊列引用傳遞給 pool.map_async() 管理的函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!