2015-02-23 41 views
2

所以,我寫了這個簡單的代碼來檢查,如果蟒蛇線程模塊是真正平行,我發現,在這種情況下,線程模塊是否真的在python中並行?還是我們需要使用多處理?

from threading import Thread, current_thread 
import multiprocessing as mp 
def callback(result): 
    print result 

def run_sql(n): 
    print current_thread() 
    for i in range(n): 
     i=i+1 
    print 'done for ', current_thread() 

if __name__=='__main__': 
    n=100000000 
    pool = mp.Pool(5) 
    threads= [ Thread(target=run_sql, args=(n,)) for i in range(5)] 
    for t in threads: 
     t.start() 
    for t in threads: 
     t.join() 

我試圖與Pool.apply_async同這實際上是平行的。

def callback(result): 
    print result 

def run_sql(n): 
    print current_thread() 
    for i in range(n): 
     i=i+1 
    print 'done for ', current_thread() 

if __name__=='__main__': 
    print datetime.datetime.now() 
    n=100000000 
    pool = mp.Pool(5) 
    for i in range(10): 
     pool.apply_async(run_sql, args= (n,),callback=callback) 
    pool.close() 
    pool.join() 

所以我的問題是什麼是使用,如果它是不是真的平行甚至可以節省工控機,並使用相同的內存區域的線程模塊的地步?另外,線程可以使用隊列或其他東西並行嗎?

回答

3

好像你儘快加入你的線程,當你開始他們:

for t in threads: 
    t.start() 
    t.join() 

IIRC,Thread.join將等待線程完成,然後再繼續(這意味着你等待第一個線程啓動第二)...

一般來說之前完成,則需要2個循環:

for t in threads: 
    t.start() 
# other stuff to do in the main thread... 
for t in thread: 
    t.join() 
+0

雅我改變了這一切。但是,與多處理相比,性能仍然不同,因爲可以稱爲更強大的線程? – TommyT 2015-02-23 19:55:45

+0

@gusc - 正是_how_你獲得的性能好處取決於你在線程中做了什麼。關鍵是,無論你在線程中做什麼,都必須釋放GIL才能實現並行代碼 - 否則,python將一次只做一件事(儘管它會在你的線程之間來回切換以確定那1件事實際上是什麼)。 'multiprocessing'將真正並行地執行你的任務(不管GIL),儘管進程之間的共享狀態更難以管理(並且代價昂貴)。 – mgilson 2015-02-23 19:57:30

+0

好的。感謝@mgilson。我會研究更多關於GIL的。在使用多處理和多線程的時候,還有其他的關鍵點,因爲我試圖設計一些面向客戶的東西,如果它產生了太多的線程/每個用戶的請求並且可能變得更難管理,那麼CPU可能會超載。 – TommyT 2015-02-23 19:59:12

相關問題