checking a thread has started

Francesco Bochicchio bockman at virgilio.it
Sun Nov 7 04:10:32 EST 2004


On Sat, 06 Nov 2004 21:58:29 +0800, Deepak Sarda wrote:

> 
> My question is: how do I check whether a call to the start() method was
> successful? If there is a mechanism by which I can get this information -
> I can try restarting/recreating the thread.
> 

I'm not aware of any method in the standard library to do this. But you
could try using events for this purpose, doing soomething like this:

class MyThread( threading.Thread ):
    def __init__(self, id ):
        threading.Thread.__init__(self)
        self.idx = id
        self.actually_started = threading.Event()
        
    def run(self):
        self.actually_started.set() # signals that the thread is started
        # thread processing goes here
        print time.time(), "Thread %s started" % self.idx 
        time.sleep(3.0)
        print time.time(), "Thread %d completed" % self.idx
#
# you could try this to serialize the thread creation
# without adding the sleep. It should be faster.        
#
def start_threads_serially( num_threads, max_wait = 2.0):
    res = []
    for i in range(num_threads):
        t = MyThread(i)
        t.start()
       # wait that the thread is started before
       # starting the next one
       t.actually_started.wait( max_wait ) 
       res.append(t)
    return res

# selftest :-)
if __name__ == '__main__':
    threadlist = start_threads_serially(100)
    for t in threadlist:
        t.join()


if __name__ == '__main__':
    threadlist = start_threads_serially(10)
    for t in threadlist:
        t.join()
    

    
        


    
        




More information about the Python-list mailing list