Interrput a thread

gervaz gervaz at gmail.com
Wed Dec 29 18:31:20 EST 2010


Hi all, I need to stop a threaded (using CTR+C or kill) application if
it runs too much or if I decide to resume the work later.
I come up with the following test implementation but I wanted some
suggestion from you on how I can implement what I need in a better or
more pythonic way. Here the code:

import os
import signal
import time
from threading import Thread, current_thread
from queue import LifoQueue, Empty

COMMAND = {"STOP": 0, "NORMAL": 1}
THREAD_NUM = 5

lq = LifoQueue()

print("{0}\n".format(os.getpid()))

class InterceptInterrupt(Exception):
    pass

class Handler:
    def __init__(self, queue):
        self._queue = queue
    def __del__(self):
        print("Bye bye!")
    def getHandler(self, signum, frame):
        print("Interrupt raised!")
        for _ in range(THREAD_NUM):
            self._queue.put((COMMAND["STOP"], None))
        raise InterceptInterrupt

h = Handler(lq)

signal.signal(signal.SIGINT, h.getHandler)

for i in range(25):
    lq.put((COMMAND["NORMAL"], i))

def do_work(queue):
    while True:
        time.sleep(5)
        try:
            cmd, value = queue.get(block=False)
            if cmd == COMMAND["STOP"]:
                print("{0}: STOP command
received!".format(current_thread().name))
                break
            elif cmd == COMMAND["NORMAL"]:
                print(value)
        except Empty:
            break

threads = [Thread(target=do_work, args=(lq,)) for _ in
range(THREAD_NUM)]

for t in threads:
    t.start()

while not lq.empty():
    try:
        time.sleep(1)
    except (IOError, InterceptInterrupt):
        break

for t in threads:
    t.join()

if lq.empty():
    print("The queue is empty.")
else:
    print("The queue is NOT empty. Some additional work has to be
done.")

Thank you,
Mattia



More information about the Python-list mailing list