[英]How do I kill a thread using the threading.event function?
我一直在等待用戶中斷后停止線程,但由於某種原因,它對我不起作用。 誰能幫忙。 問題是該程序只是忽略了鍵盤中斷錯誤,在鍵盤中斷后它沒有關閉。
#!/usr/bin/env python
#
#
from time import sleep
from Queue import Queue
from threading import Thread,Event,Lock
def Count():
global Exit
for i in range(5):
try:
if not Exit.is_set():
with l:
print i;sleep(2)
except KeyboardInterrupt:
Exit.set()
if __name__ == '__main__':
l = Lock()
q = Queue()
Exit = Event()
for i in range(2):
Bot = Thread(target=(Count)).start()
q.put(Bot)
#q.join()
#OutPut
0
1
^C2
3
4
0
Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
尚不清楚您要完成什么。 所以我重組了您的代碼。
from time import sleep
from threading import Thread, Event
def count():
global exit_event
for i in range(5):
try:
if not exit_event.is_set():
print i
sleep(2)
except KeyboardInterrupt:
print "Interrupt in thread"
exit_event.set()
exit_event = Event()
bot = Thread(target=count)
bot.start()
while not exit_event.is_set():
try:
sleep(0.1)
except KeyboardInterrupt:
print "Interrupt in main loop"
exit_event.set()
bot.join()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.