2015-09-04 43 views
1

運行多個功能,我有以下代碼如何在同一時間

my_func1() 
my_func2() 
my_func3() 
my_func4() 
my_func5() 

是否有可能在同一時間來計算功能的數據,而不是一個又一個?

+0

你絕對確信你需要這麼做嗎? – TigerhawkT3

+2

https://docs.python.org/2/library/multiprocessing.html – MattDMo

+0

在同一時間?可能不會,但是你可以對它進行多處理,所以人們不必等待另一個完成 – taesu

回答

1

可以使用多或線程在Python犯規 線程實際上是在並行運行,但允許您在同一時間運行函數的函數(和Python會遍歷他們,一次做幾行)

與多處理它們將並行運行(假設你有多個CPU核心),但他們不會共享內存。 這裏是多處理

from multiprocessing import Process 
p = Process(target=myfunc1) 
p.start() 
p2 = Process(target=myfunc2) 
p2.start() 
# and so on 
p.join() 
p2.join() 
# the join means wait untill it finished 

樣品,你可以閱讀更多關於它在這裏:

https://docs.python.org/2/library/multiprocessing.html

https://wiki.python.org/moin/GlobalInterpreterLock

+0

這絕對計算我的數據a很快,但由於某些原因,我無法在計算時顯示數據,如果您知道我的意思。 – PiccolMan

+0

我認爲我的顯示功能在多進程完成之前調用自己。在多進程功能完成後有沒有辦法調用我的顯示功能? – PiccolMan

+0

是的,如果在所有進程中調用p.join()之後調用它。加入意味着它會等待,直到它完成,所以你可以等待,直到他們都完成了,而不僅僅是調用你的顯示功能 – DorElias

2
import thread 


thread.start_new_thread(my_func1,()) 
thread.start_new_thread(my_func2,()) 
thread.start_new_thread(my_func3,()) 
thread.start_new_thread(my_func4,()) 
thread.start_new_thread(my_func5,()) 

你可以跟帖像

+0

在python 3上做這個工作嗎? – PiccolMan

+0

看看這個答案爲一個深入的答案:http://stackoverflow.com/questions/6319268/what-happened-to-thread-start-new-thread-in-python-3 – Yurippenet

0
from multiprocessing import Process 
from time import sleep 

def f(name): 
    print 'hello', name 
    sleep(1) 

考慮以上:

,如果你要這樣做:

f('bob') #start 
f('alice') #wait until bob's done 
f('jack') #wait until alice is done 
f('cake') #wait until jack is done 
f('paul') #wait until cake is done 
print 'done' 

你最終會等待5秒鐘,你看到done

之前但是,如果你使用多,你可以生成多個進程同時運行的功能。

Process(target=f, args=('bob',)).start() #start now 
Process(target=f, args=('alice',)).start() #start now 
Process(target=f, args=('jack',)).start() #start now 
Process(target=f, args=('cake',)).start() #start now 
Process(target=f, args=('paul',)).start() #start now 
print 'done' #start now 
1

我喜歡的方式是使用concurrent.futures它是一個標準的Python庫(3.2及以上版本或可作爲單獨的軟件包爲Python 2.7):

from concurrent.futures import ThreadPoolExecutor 

executors_list = [] 

with ThreadPoolExecutor(max_workers=5) as executor: 
    executors_list.append(executor.submit(my_func1, arg1, arg2)) 
    executors_list.append(executor.submit(my_func2, arg1, arg2)) 
    executors_list.append(executor.submit(my_func3, arg1, arg2)) 

for x in executors_list: 
    print(x.result()) 

這將同時運行my_func1my_func2my_func3,將arg1arg2傳遞給每一個。一旦它們可用,它將按順序打印所有結果。