Python threads ( termination )

Dan Parisien dan at eevolved.com
Fri Feb 16 18:23:39 CET 2001


aboufer at atlsci.com wrote:

> Greetings,
> 
>     I am trying to write a multi-threaded app using python, and I am
> trying to find
> a way to stop/terminate a thread from within another.
> 
> Here is an example :
> 
> import threading
> 
> mySuccess = 0
> 
> class MyThread( threading.Thread) :
>     def __init__( self, name='hello') :
>         threading.Thread.__init__( self, name=name)
> 
>     def run(self) :
>         global mySuccess
>         import random
> 
>         for x in range(10) :
>                 threading._sleep( random() )
>                 print 'Hello ', x
> 
>         mySuccess = 1
> 
> myTest() :
>     t1 = MyThread()
>     t1.start()
> 
>     t1.join( 0.1 )
> 
>     if mySuccess == 1 :
>         print 'Thread exited okay'
>     else :
>         print 'Thread did not respond !!'
>         I need a way to kill thread t1 here <------------------------
> 
> if __name__ == '__main__' :
>         myTest()
> 
> 
> In this example, my function myTest calls join() on thread t1, with a
> specified time_out. What I would like to
> do is to terminate/stop thread t1 if it does not respond within timeout.
> 
> 
> 
> Thanks all
> 

You could use 2 threading.Event instances to communicate between threads 
and have the 'bad' thread terminate itself.

There is no real way to terminate a thread from another thread...

Dan




More information about the Python-list mailing list