Terminating a thread from the parent

flupke flupke at nonexistingdomain.com
Tue May 24 03:32:34 EDT 2005


DE wrote:
> Hello,
> 
> I have an app with embedded Python. Python scripts create their own
> threads and I need to terminate these threads at the point where the
> user wants to leave the application. I use threading.Thread as base
> classes.
> 
> I have tried to use call the join method of the python thread objects
> from C++. But although the call succeeds, the threads don't exit.
> 
> What is the proper way of doing this ? (e.g. how does the python shell
> do this ? )
> 
> Thanks in advance,
> 
> Devrim.
> 

I found this example somewhere. It shows how you terminate a thread.
As Peter said, it's the thread that terminates itself.

#!/usr/bin/env python
"""
testthread.py
An example of an idiom for controling threads

Doug Fort
http://www.dougfort.net
"""

import threading

class TestThread(threading.Thread):
     """
     A sample thread class
     """

     def __init__(self):
         """
         Constructor, setting initial variables
         """
         self._stopevent = threading.Event()
         self._sleepperiod = 1.0

         threading.Thread.__init__(self, name="TestThread")

     def run(self):
         """
         overload of threading.thread.run()
         main control loop
         """
         print "%s starts" % (self.getName(),)

         count = 0
         while not self._stopevent.isSet():
             count += 1
             print "loop %d" % (count,)
             self._stopevent.wait(self._sleepperiod)

         print "%s ends" % (self.getName(),)

     def join(self,timeout=None):
         """
         Stop the thread
         """
         self._stopevent.set()
         threading.Thread.join(self, timeout)

if __name__ == "__main__":
     testthread = TestThread()
     testthread.start()

     import time
     time.sleep(10.0)

     testthread.join()

Benedict



More information about the Python-list mailing list