這是一個解決方案,但它不完全像你問,因爲它很複雜,殺死一個線程。它更好地讓線程自行終止,所有線程默認爲守護進程= False(除非它的父線程是守護進程),所以當主線程死亡時,線程將活着。將它設置爲true,它將隨着主線程而死。
基本上你所做的只是啓動一個Thread
並給它一個運行方法。您需要能夠傳遞參數,因爲您可以看到我傳遞了一個參數args=
以傳遞給目標方法的值。
import time
import threading
def otherdef(num1, num2, num3):
#Inside of otherdef we use an event to loop on,
#we do this so we can have a convent way to stop the process.
stopped = threading.Event()
#set a timer, after 10 seconds.. kill this loop
threading.Timer(10, stopped.set).start()
#while the event has not been triggered, do something useless
while(not stopped.is_set()):
print 'doing ', num1, num2, num3
stopped.wait(1)
print 'otherdef exiting'
print 'Running'
#create a thread, when I call start call the target and pass args
p = threading.Thread(target=otherdef, args=(1,2,3))
p.start()
#wait for the threadto finish
p.join(11)
print 'Done'
它仍不清楚,如果你想有一個進程或線程,但如果你想有一個Process
進口多,並切換到threading.Thread(
multiprocessing.Process(
,一切保持不變。
來源
2011-06-29 16:03:13
Nix
你說'在一個新的線程'你的意思是'在一個新的過程' – Nix
而不是殺死它,爲什麼你沒有過程中止10分鐘後過去? – Nix