简体   繁体   中英

How do I kill a thread using the threading.event function?

I been looking at stopping a thread after user interruption, but for some reason it's not working for me. Can anyone help. The issue is the program just ignores the keyboard interruption error, it's not shutting down after the keyboard interruption.

#!/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

It is not entirely clear what you are trying to accomplish. So i restructured your code.

  1. I have removed the queue that your were putting things into, but not taking anything out of.
  2. I removed the lock, that was not being invoked by more than one thread, and worse was holding the lock around a sleep.
  3. I join the thread at the end of the main loop, instead of joining a queue which will never be empty.
  4. And lastly, I check for a keyboard interrupt in all of the threads.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM