#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2005
    Posts
    2
    Rep Power
    0

    Stopping a thread the hard way


    I want to kill a running program by hitting ctrl-c but it uses threads. I *know* threads are not killable but there must be a way to do this.
    Here's my setup: a telnet server runs, accepting logging, processing user input, etc. It's a MOO, in fact. But I'm trying to implement timed events and I don't see another way to do this than by using threads. While the server handles connections, a thread checks every second if something has to be done (like kicking out idle players, handling combat or specific timed actions, etc.)

    The whole thing is a console server, ctrl-c is used to shutdown the server. I tried trapping KeyboardInterrupt but it didn't work:

    Code:
    class Threads(Thread):
    	def __init__(self):
    		self.stopevent = Event()
    		Thread.__init__(self)
    	def run(self):
    		while not self.stopevent.isSet():
    			try:
    				print "running"
    				time.sleep(3)
    			except KeyboardInterrupt:
    				self.stopevent.set()
    				print "Terminating"
    The previous example can only be shutdown by manually killing the python process. Ugly.
    The following version doesn't work either. It stops on ctrl-c but the thread doesn't even start.

    Code:
    class Threads(Thread):
    	def __init__(self):
    		self._stopevent = Event()
    		Thread.__init__(self)
    	def run(self):
    		while not KeyboardInterrupt:
    			print sessions
    			time.sleep(5)
    Instead of having the thread pool a certain variable and if it's set terminate itself, is it possible to trap the thread to stop on ctrl-c? I know that python forces you to cleanly terminate your threads but I need to be able to simply shutdown the server with a simple command.
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2005
    Posts
    8
    Rep Power
    0
    I don't know for sure myself, but I remembered reading the Python Cookbook; there was a recipe on threading. The author commented on something about there is no way to gracefully stop a Python thread, except asking it to stop. He did some sort of example on interrupt requests, where he created a separate thread to monitor the interrupt request and then that thread would insert the except. Rather than in yours, you are catching the exception. If I remembered correctly, you would need a separate thread to handle the exception then tell your other threads. In any case, you should take a look at the book to find out more. I can't really tell you much since I am trying to fix a threading problem of my own.

IMN logo majestic logo threadwatch logo seochat tools logo