views:

66

answers:

1

I would like 3 Threads in Python to run for n seconds. I want to start them all at the same time and have them finish at the same time (within milliseconds). How do I do this?

threading.Timer only starts after the previous one has been completed.

+2  A: 
import threading 
import time

class A(threading.Thread):
  def run(self):
     print "here", time.time()
     time.sleep(10)
     print "there", time.time()


if __name__=="__main__":
  for i in range(3):
     a = A()
     a.start()

prints:

here 1279553593.49
here 1279553593.49
here 1279553593.49
there 1279553603.5
there 1279553603.5
there 1279553603.5
adamk
See Dan's comment at the original post. This can't be guaranteed to finish (even sort-of) simultaneously (some threads might not receive CPU time, for instance). Also, using "sleep" isn't really practical, supposedly the threads should be doing something in the meantime...
rbp
@rbp: you're right, but the OP didn't indicate what each thread has to do - if one thread has much more work than the other, then I don't really see the point of the question... I think that as a practical solution, this probably answers the OP's needs (either way the threads will never finish "at the same time").
adamk