2015-08-15 36 views
1

我想運行多個線程,每個線程都有相同的目的,但每個使用不同的方法。因此,當他們中的一個人發現數據時,我不再需要其他人,我可以殺死他們。我已經讀過,殺死線程並不好,因爲他們可能會用關鍵資源做某件事。所以我的問題是,如何在不做壞事情的情況下實現這種事情?運行多個線程,直到一個退出python

回答

2

您可以使用multiprocessing

比方說,我們有兩個函數計算Pi的值,calculate1()calculate2()。在這種情況下,calculate2()更快。

import multiprocessing 
import time 

def calculate1(result_queue): 
    print "calculate1 started" 
    time.sleep(10) 
    result = 3.14 
    result_queue.put(result) 
    print "calculate1 found the result!" 

def calculate2(result_queue): 
    print "calculate2 started" 
    time.sleep(2) 
    result = 3.14 
    result_queue.put(result) 
    print "calculate2 found the result!" 

result_queue = multiprocessing.Queue() 

process1 = multiprocessing.Process(target=calculate1, args=[result_queue]) 
process2 = multiprocessing.Process(target=calculate2, args=[result_queue]) 

process1.start() 
process2.start() 

print "Calculating the result with 2 threads." 

result = result_queue.get() # waits until any of the proccess have `.put()` a result 

for process in [process1, process2]: # then kill them all off 
    process.terminate() 

print "Got result:", result 

此輸出:

calculate1 started 
calculate2 started 
calculate2 found the result! 
Got result: 3.14 
+0

太好了!正是我需要的,謝謝。 – pystudent

+0

沒有隊列可以做到這一點嗎?因爲我更喜歡,如果可能的話,在不改變方法的情況下(添加參數和result_queue.put ...) – pystudent

+0

@pystudent我不確定。但是,如果您不想修改原始函數,則可以考慮製作包裝函數。 – Sait

相關問題