2014-06-13 34 views
1

我想確保以下兩個並行進程一個接一個地執行。特別是,我希望首先實現十個f函數,並在完成該部分之後,實現十個g函數。有誰知道我應該如何修改我的代碼?如何隨後運行兩個並行進程?

from multiprocessing import Process 
import time 
import random 

wait_low = 0.1 
wait_high = 15 

def f(i): 
    time.sleep(random.uniform(wait_low, wait_high)) 
    print 'hello'+str(i) 

def g(i): 
    time.sleep(random.uniform(wait_low, wait_high)) 
    print 'hey'+str(i) 


if __name__ == '__main__': 
    for j in range(10): 
     p = Process(target=f, args=(j,)) 
     p.start() 
    p.join() 

    print "switch" 

    # comment 
    for j in range(10): 
     q = Process(target=g, args=(j,)) 
     q.start() 
    q.join() 

    time.sleep(5) 

    print "I'm done" 

而且我得到的結果是:

hello2 
hello0 
hello1 
hello5 
hello6 
hello8 
hello3 
hello7 
hello9 
switch 
hey6 
hey3 
hello4 
hey9 
hey8 
I'm done 
hey2 
hey0 
hey1 
hey5 
hey7 
hey4 

非常感謝!

回答

3

所有f的和g的需要連接。

if __name__ == '__main__': 
    fs = [] 
    for j in range(10): 
     p = Process(target=f, args=(j,)) 
     p.start() 
     fs.append(p) 

    for f in fs: 
     f.join() 

    print "switch" 

    # comment 
    gs = [] 
    for j in range(10): 
     q = Process(target=g, args=(j,)) 
     q.start() 
     gs.append(q) 

    for g in gs: 
     g.join() 

    print "I'm done" 

輸出:

hello2 
hello8 
hello5 
hello6 
hello9 
hello1 
hello4 
hello3 
hello7 
hello0 
switch 
hey0 
hey7 
hey2 
hey8 
hey4 
hey3 
hey1 
hey9 
hey5 
hey6 
I'm done 
+0

這非常非常感謝 – user3698176

+0

@ user3698176,沒問題,請接受的解決方案。!。 – Fabricator

2

你的問題是在你的代碼中,你只加入了你在循環中產生的最後一個進程,你可以在之前的完成之前繼續,這會導致輸出的交錯。

你可以使用一個處理池:

from multiprocessing.pool import Pool 
import random 
import time 

wait_low = 0 
wait_high=1 
def f(i): 
    time.sleep(random.uniform(wait_low, wait_high)) 
    return 'hello'+str(i) 

def g(i): 
    time.sleep(random.uniform(wait_low, wait_high)) 
    return 'hey'+str(i) 


pool = Pool() 
for output in pool.imap_unordered(f, range(10)): 
    print output 
for output in pool.imap_unordered(g, range(10)): 
    print output 
0

使用阻斷map功能而不是做你自己的基本事實的工作。你可以用內置的multiprocessing,但因爲我懶我只是做了它的解釋(這樣做需要的multiprocessing叉叫pathos

>>> from pathos.multiprocessing import ProcessingPool as Pool 
>>> import time 
>>> import random 
>>> 
>>> wait_low = 0.1 
>>> wait_high = 15 
>>> 
>>> def f(i): 
... time.sleep(random.uniform(wait_low, wait_high)) 
... print 'hello'+str(i) 
... 
>>> def g(i): 
... time.sleep(random.uniform(wait_low, wait_high)) 
... print 'hey'+str(i) 
... 
>>> 

以下然後創建並啓動地圖

>>> p = Pool() 
>>> r = p.map(f, range(10)); print "switch"; r = p.map(g, range(10)); print "I'm done" 
hello6 
hello2 
hello1 
hello0 
hello5 
hello8 
hello3 
hello4 
hello7 
hello9 
switch 
hey5 
hey6 
hey7 
hey1 
hey9 
hey4 
hey8 
hey3 
hey0 
hey2 
I'm done 
>>> 

你可以得到pathos這裏:https://github.com/uqfoundation