[Tutor] Killing a thread from main - was RE: "Lock"ing threads

Kent Johnson kent37 at tds.net
Tue Aug 30 04:51:29 CEST 2005


Hans Dushanthakumar wrote:
> Thanks Kent
> 
> How do I send a signal from the main thread to stop execution of a child
> thread?

You have the right idea - set some kind of flag that the thread checks - but you reused the name 'stop' so when you execute incr_num_thread.stop() you are retrieving the 'stop' attribute of incr_num_thread (which is the integer 0) rather than the 'stop' attribute of class shownum (which is the method you want). Then you try to call the integer (by the ()) and get an error.

This recipe has a more sophisticated version of the same idea:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448

Kent
>    
> I tried the foll:, but got an error:
> Other than by this method, is there any other mechanism to stop a
> thread?
> 
> import threading
> import time
> 
> class shownum(threading.Thread):
>     
>     def __init__(self, start_num):
>         threading.Thread.__init__(self)
>         self.num = start_num
>         self.stop = 0
>         
>     def run(self):
>         for i in range(12):
>             time.sleep(1)
>             print "shownum: ", self.num
>             self.num = self.num + 1
>             if self.stop == 1:
>                 break            
> 
>     def stop(self):
>         self.stop = 1
> 
>     def chng(self):
>         self.num = 1
>         
> incr_num_thread = shownum1(201)
> incr_num_thread.start()
> 
> time.sleep(3)
> incr_num_thread.chng()
> time.sleep(3)
> incr_num_thread.stop()
> 
> 
> Output:
> 
> shownum:  201
> shownum:  202
> shownum:  1
> shownum:  2
> shownum:  3
> Traceback (most recent call last):
>   File "H:\Docs\PyScripts\test_threads.py", line 31, in ?
>     incr_num_thread.stop()
> TypeError: 'int' object is not callable
> shownum:  4
> shownum:  5
> shownum:  6
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list