Help: puzzled about threads

Anton Muhin antonmuhin at
Mon Feb 17 15:44:25 CET 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."""

#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

     def __get_id(self):
         return self.__id

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

     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__,

     def __bootstrap(self):
         #Set id of the thread.
         assert self.__status == Thread.INIT
         self.__id = CurrentThreadId()
             self.__status = Thread.RUNNING
             #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:",

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

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

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

More information about the Python-list mailing list