Threading-> Stopping
David Wahler
dwahler at gmail.com
Fri Nov 4 11:33:02 EST 2005
Tuvas wrote:
> Is there a way to stop a thread with some command like t.stop()? Or any
> other neat way to get around it? Thanks!
Sadly, no. While Java and many other programming languages have an
interrupt() primitive, Python does not. You can approximate this by
using a global variable to tell the thread when to stop, for example:
shutdown = False
class MyThread(Thread):
def run(self):
while not shutdown:
# do whatever
def kill_thread():
shutdown = True
There's no general way to wake up a thread that's blocked--you have to
satisfy the condition that's causing it to block. If it's waiting for
input from a Queue, you have to push a dummy value down it to wake up
the thread and give it a chance to check the shutdown flag. If it's
blocking to do I/O, you'll have to use select() and provide a timeout
value to check the flag periodically.
-- David
More information about the Python-list
mailing list