簡體   English   中英

如何使用threading.event函數殺死線程?

[英]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

尚不清楚您要完成什么。 所以我重組了您的代碼。

  1. 我已經刪除了您正在放入但沒有取出任何東西的隊列。
  2. 我刪除了鎖,該鎖沒有被多個線程調用,更糟糕的是,該鎖一直保持睡眠狀態。
  3. 我在主循環末尾加入線程,而不是加入永遠不會為空的隊列。
  4. 最后,我檢查所有線程中的鍵盤中斷。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM