Help: puzzled about threads

Gonçalo Rodrigues op73418 at mail.telepac.pt
Mon Feb 17 12:21:15 EST 2003


On Mon, 17 Feb 2003 17:44:25 +0300, Anton Muhin <antonmuhin at sendmail.ru>
wrote:

>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 

Yes. Prompted by your earlier reply I arrived at this same conclusion.

>Thread class. Here comes my variant that seems to work although I didn't 
>test it a lot.

Also prompted by your reply I changed my implementation. It is pretty
much like yours below, except I use a reentrant lock that signals the
thread has started running. In this way I can hold off the actual
running of the thread for awhile to do additional initialization tasks
that are best left to the main (or parent or...) thread.

>
>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)

Thanks for everything, you really helped me.

With my est regards,
G. Rodrigues





More information about the Python-list mailing list