2012-11-24 100 views
4

當第二個線程完成時,有什麼辦法可以停止第一個線程嗎?如何在python中完成第二個線程時停止第一個線程?

實施例:

from functools import partial 

import threading 

def run_in_threads(*functions): 
    threads=[] 

    for function in functions: 
     thread=threading.Thread(target=function) 
     thread.start() 
     threads.append(thread) 

    for thread in threads: 
     thread.join() 

def __print_infinite_loop(value): 
    while True:print(value) 

def __print_my_value_n_times(value,n): 
    for i in range(n):print(value) 

if __name__=="__main__": 
    run_in_threads(partial(__print_infinite_loop,"xyz"),partial(__print_my_value_n_times,"123",1000)))))) 

在上述axample i的線程兩個功能運行,我有當所述第二結束停止第一線程。我讀到它支持的事件,但不幸我沒有使用它。

回答

1

你可以使用一個threading.Event這樣的:

import functools 
import threading 

def run_in_threads(*functions): 
    threads = [] 

    for function in functions: 
     thread = threading.Thread(target = function) 
     thread.daemon = True 
     thread.start() 
     threads.append(thread) 

    for thread in threads: 
     thread.join() 

def __print_infinite_loop(value, event): 
    while not event.is_set(): 
     print(value) 

def __print_my_value_n_times(value, n, event): 
    for i in range(n): 
     print(value) 
    event.set() 

if __name__ == "__main__": 
    event = threading.Event() 
    infinite_loop = functools.partial(__print_infinite_loop, "xyz", event) 
    my_values = functools.partial(__print_my_value_n_times, "123", 10, event) 
    run_in_threads(infinite_loop, my_values) 
+0

非常感謝,您的解決方案的偉大工程! –

相關問題