2017-09-04 80 views
0

有可能有幾個子進程運行一些計算,然後將結果發送到主進程(例如,更新PyQt ui),但進程仍在運行他們發回數據並再次更新ui? 使用multiprocessing.queue時,似乎數據只能在進程終止後才發回。 所以我想知道這種情況是否可能。提前致謝!Python多處理 - 子進程不斷髮回結果並繼續運行

回答

1

我不知道你的意思是「使用multiprocessing.queue,它似乎只能在進程終止後發回數據」。這正是Multiprocessing.Queue設計的用例。

PyMOTW是整個Python模塊負載(包括多處理)的絕佳資源。看看這裏:https://pymotw.com/2/multiprocessing/communication.html

如何從一個孩子正在發送消息給使用多和循環家長一個簡單的例子:

import multiprocessing 

def child_process(q): 
    for i in range(10): 
     q.put(i) 
    q.put("done") # tell the parent process we've finished 

def parent_process(): 
    q = multiprocessing.Queue() 
    child = multiprocessing.Process(target=child_process, args=(q,)) 
    child.start() 
    while True: 
     value = q.get() 
     if value == "done": # no more values from child process 
      break 
     print value 
     # do other stuff, child will continue to run in separate process 
+0

我不知道我的理解。你的意思是如果完成需要超過一定的時間,你想終止這個過程?如果這是你想要的,那麼你應該看看信號包中的signal.alarm https://docs.python.org/2/library/signal.html – wolfson109

+0

謝謝!所以我想知道一個情況,如果我想從子進程得到一些結果而不等待它終止。子進程始終運行並不斷髮送數據。那可能嗎? – nmvhs

+0

是的,你只需要在每次產生一個新值時調用queue.put的循環中運行你的子進程。然後父線程可以運行一個不同的循環,每次都調用queue.get。 – wolfson109

相關問題