Stopping a Python thread

Status
Not open for further replies.

gwenkhan

Ars Scholae Palatinae
735
I'm rather new to Python and I'm trying to solve a small problem with Threads. This might be "oh that's easy, it's simple_method()", or it could be a "sorry, that's totally impossible", I'm not sure.

I know that killing a thread externally is impossible, but that's not what I want to do here. What I have is a thread that has to stop itself, without having to reach the end of the run() method. Specifically, what I have is a thread that needs to complete all its work within a given amount of time, or else timeout with some special timeout-handling code if it can't:
Code:
class MyThread(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.timer = Timer(5.0, self.timeout)

    def run(self):
        self.timer.start()
        # ... do stuff ....
   
     def timeout(self):
          # timeout code
          # End of timeout code - thread has done internal cleanup and it's perfectly acceptable to kill it here
So run() runs the thread's normal code, and timeout() is the out-of-time code. The thing is, if timeout() runs, the thread needs to go away when that method is done, it cannot go back to run() and keep executing code, and just blocking forever isn't great either (lots of these threads will be created). Without a goto to the end of my run() method, how can I accomplish this? Or, do I need to rethink my solution entirely and not rely on a Timer started when the thread is?

Thanks.
 

herko

Tone down Your Control issues.
7,012
Moderator
I suspect that what you want to do is impossible in a supported fashion. First of all, Timer is itself a Thread, and will therefore call the timeout() method in a different thread of execution. It won't interrupt the execution of MyThread.

Second, Python Threads provide no mechanism for thread control. You can't set their priority, you can't pause them, and in general they aren't even very "good" threads. There's a Global Interpreter Lock that only lets a single Python thread run at a time. Aside from blocking I/O, python Threads are not very useful.

Finally, killing a thread arbitrarily may not be the best of program designs either. What larger goal do you want to achieve? There may be a better way of doing it.

The 'proper' way of implementing what you want is checking regularly how much time has elapsed inside of run() and aborting the operation if it is taking too long. That may be impossible depending on what you need run() to do,

After all those caveats, here's a way to raise an Exception in another thread, which may accomplish what you want. I haven't tried it.
 

gwenkhan

Ars Scholae Palatinae
735
herko":9gzgiabp said:
Stanley Turnteen":9gzgiabp said:
http://docs.python.org/library/thread.html

thread.exit()
Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.

Raising SystemExit in timeout() will just execute it inside the Timer thread, which won't kill MyThread.

And in any event, I'm using the highlevel "threading" library with Thread objects, not the older one; the new ones don't even have exit()

I may have found another way though: the code is actually fpr a wrapper around a networking object which times out if no data is received, and the socket methods provide their own timeout functionality, so I think I'll use that instead. Thanks anyway!
 

karmakaze

Ars Tribunus Militum
1,700
Subscriptor
If this code needs to be pretty performant, does a lot of work in parallel (e.g. communicating with multiple clients as a server), and is mainly spending it's time waiting on I/O (e.g. network traffic, databases, disk activity), check out Twisted Python: http://twistedmatrix.com/documents/curr ... /examples/

It's a bit to wrap you head around (I would suggest the Oreily book, it's a little out of date now but still a great primer), but if you're really interested in performance it's the way to go. Honestly I have no idea how to do traditional threading in Python, and don't really want to, since Twisted abstracts most of that away. Threads in Python are also pretty restricted by the Global Interpreter Lock (http://wiki.python.org/moin/GlobalInterpreterLock), since only one thread can be running "Python code" at a time (though really most apps spend most of their time in inner binary libraries that have hopefully released the GI lock).
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Just a note that any sort of 'kill this thread externally' is *only* ever legit in a world of proper threads (as opposed to green threads or some other construct) as anything but "I am taking the process down now I just want things to die asap" is a big no no. It is fundamentally flawed in that you can always toast arbitrary parts of your processes state while doing this.

It is possible in some runtimes to have critical sections which will disallow the abort within them but they are incredibly constrained as to what you can do within them (i.e. next to no useful work) and require _serious_ ninja level understanding of the target environment before going anywhere near them, if you're trying to abort threads you aren't at that level(1).

If you are calling some function which does not itself provide a timeout you're pretty SOL I'm afraid, even more so in python due to the GIL.

1) I am absolutely not at the level required to write this sort of thing either
 

karmakaze

Ars Tribunus Militum
1,700
Subscriptor
I would hope most green threading systems (which I'm not sure Twisted counts as, it's more cooperative timeslicing) have an API for cancelling green threads gracefully. I know Twisted has defer.cancel(), but I'm actually not sure how that gets carried down to the lower levels (unless, say, the DBAPI wrappers return a Deferred subclass whose cancel method aborts the DB transaction when cancel is chained down to it).

I see Stackless Python (which I have no actual experience with) has a kill() method which raises a TaskletException in the running tasklet function. But anyways, I stray too far off topic..
 
Status
Not open for further replies.