2016-01-21 108 views
0

我需要一些幫助來解決這個問題。反覆產卵的過程相同

我遇到的問題是,進程1運行一個for循環裏面,數據收集和我需要產卵的過程來分析它。

這段代碼我只會創建每個進程一次,如何重複每個數據的循環過程2? TIA

from multiprocessing import Process, Queue 


def data(q): 
    dosmth() 
    for i in range(5): 
     fetch_data() 
     q.put('data has been added') 


def analysis(q): 
    msg = q.get() 
    print(msg) 
    process_data() 

if __name__ == '__main__': 
    q = Queue() 
    processes = [Process(target=data, args=(q,)), Process(target=analysis, args=(q,))] 
    for p in processes: 
     p.start() 
    for p in processes: 
     p.join() 

回答

1
from multiprocessing import Process, Queue 


def data(q): 
    dosmth() 
    processes = [] 
    for i in range(5): 
     fetch_data() 
     q.put('data has been added') 
     processes.append(Process(target=analysis, args=(q,))) 
    for p in processes: 
     p.start() 
    for p in processes: 
     p.join() 


def analysis(q): 
    msg = q.get() 
    print(msg) 
    process_data() 

if __name__ == '__main__': 
    q = Queue() 
    processes = [Process(target=data, args=(q,))] 
    for p in processes: 
     p.start() 
    for p in processes: 
     p.join() 

甚至更​​好直接傳遞數據,而不是排隊分析。不好的部分是,如果你獲得大量的數據,你會開始很多過程,效率低下。

另一種方法可以讓分析循環,而q.get(),這樣分析每次可以處理多個數據。然後,您可以實例化儘可能多的分析,而不管其數據是多少。