3

It seems that if you have a loop of n threads and join them one by one with the timeout t, the actual time you take is n * t because the beginning to count timeout of one child thread is the ending time of last child thread. Is there any way to reduce this total time to t not n*t?

Tiancheng Liu
  • 782
  • 2
  • 9
  • 22

2 Answers2

2

Yes, you can calculate an absolute timeout, and recompute your remaining relative timeout before every join:

# Join the_threads, waiting no more than some_relative_timeout to
# attempt to join all of them.

absolute_timeout = time.time() + some_relative_timeout

for thr in the_threads:
  timeout = absolute_timeout - time.time()
  if timeout < 0:
    break
  thr.join(timeout)
  if thr.isAlive():
    # we timed out
  else:
    # we didn't

Now, whether or not you *should* do this is a bit opaque. It may be better to have "daemon" worker threads communicate their completion by other means: a global state table, pushes of "done" messages to a queue, etc.

pilcrow
  • 56,591
  • 13
  • 94
  • 135
-1

The reason to join a thread is so that the calling thread waits for the joined thread to finish. If the child thread terminates (either on purpose or due to an unhandled exception), the the parent's join() call will return.

If you are joining every child thread and then waiting the for the timeout to complete, then your main thread isn't actually respecting the point of join(), which is to cease execution until the child threads terminate.

If you expect your child thread to complete in under the timeout, then the main thread shouldn't ever need to wait for the full timeout. If you expect the child thread to operate for longer than the timeout and you don't want the parent thread to stop execution while the child operates, then why have the parent join() the child at all?

Zachary Cross
  • 2,298
  • 1
  • 15
  • 22
  • My case is I have a timeout for every child thread. In this timeout, parent thread will block and wait for child thread. After this timeout, parent thread will go on to execute no matter the child thread is terminated or not. – Tiancheng Liu Oct 27 '17 at 19:48