Help: puzzled about threads

Anton Muhin antonmuhin at sendmail.ru
Mon Feb 17 09:44:25 EST 2003


Here comes more elaborated answer.

The problem is that your thread didn't manage to start *BEFORE* main 
thread finishes. Actual problem is hidden in your implemetation of 
Thread class. Here comes my variant that seems to work although I didn't 
test it a lot.

HTH, Anton

#Import modules.
import thread

import time #You forgot to import this one

#Global thread functions.
def CurrentThreadId():
     """Returns the current thread id."""
     return thread.get_ident()


#Module specific exceptions.
class ThreadError(thread.error):
     """The ThreadError exception class."""
     pass


#The Thread class.
class Thread(object):
     """The Thread class."""
     INIT = 0               # Three possible states of thread
     RUNNING = 1
     STOPPED = 2

     def __init__(self):
         """The initializer."""
         super(Thread, self).__init__()
         self.__id = None
         self.__status = Thread.INIT   # The less variables , the better

     #Properties.
     def __get_id(self):
         return self.__id

     id = property(__get_id, None, None,
                   "Thread id. None means the thread has not started.")

     #Methods.
     def isStopped(self):
         """Return 1 if the thread is *stopped*, 0 otherwise."""
         #Guarantee thread is initialized.
         return self.__status == Thread.STOPPED

     def __repr__(self):
         #Guarantee thread is fully initialized.
         stati = {Thread.INIT: "Init", Thread.RUNNING: "Running", 
Thread.STOPPED: "Stopped"}

         return "<%s(%s, %s)>" % (self.__class__.__name__,
                                  self.__id,
                                  stati[self.__status])

     def __bootstrap(self):
         #Set id of the thread.
         assert self.__status == Thread.INIT
         self.__id = CurrentThreadId()
         try:
             self.__status = Thread.RUNNING
             self.run()
         finally:
             #Signal the thread has stopped running.
             self.__status = Thread.STOPPED

     def start(self):
         id = thread.start_new_thread(self.__bootstrap, ())
         return id

     def run(self):
         """The run method."""
         raise NotImplementedError("You must override the run method.")


if __name__ == '__main__':
    #A mock thread that dies immediately.
     class MockThread(Thread):
         def run(self):
             print "Mock:", self.id
             return

     mockthread = MockThread()
     id = mockthread.start()

#    time.sleep(0.01)
     #Sleep wait until thread dies.
     while not mockthread.isStopped():
         print "Sleeping..."
         time.sleep(0.001)

     if not mockthread.id == id:
         print "Error: thread id mismatch. thread id is %s." % mockthread.id
     print repr(mockthread)





More information about the Python-list mailing list