2014-12-24 112 views
2

我想只有一個線程是活躍的,這裏是算法:Python的線程,殺死線程

def myfunction(update): 
    if threading.activeCount >=1: 
     # kill all previous threads 
    while true: 
     # some execution 


while true: 
    t = threading.Thread(myfunction, args=([update])) 
    t.start() 

所以在這裏線程便會在myfunction的無限循環,所以開始新的之前,我需要關閉之前的一,請指導我

+0

你檢查了嗎? https://docs.python.org/2/library/threading.html#threading.Thread.join,併爲它的樂趣:http://bit.ly/1wDBDd9 – miraculixx

+0

@miraculixx我不需要等待,我需要強制線程停止 – Hackaholic

+0

看看這裏http://stackoverflow.com/questions/14482230/why-does-the-python-threading-thread-object-has-start-but-not-stop –

回答

2

你不能殺死線程,你的函數必須以某種方式返回。那麼,訣竅就是編寫你的函數,以便知道何時停止它的操作並返回。當然,這非常依賴於上下文。它通常將您的代碼實現爲具有知道該做什麼的'close'方法的類。例如,

  • 如果線程正在等待子進程,close可能會終止子進程。

  • 如果線程進行了睡眠,您可以改用事件 - 關閉會設置事件。

  • 如果你的線程在隊列中等待,你可以有一個特殊的方法來告訴它返回。