0

I am working on a code I haven't written myself.

I found the following line of code: thread.join(timeout=0.0) applied on a threading.Thread object.

What could be the purpose of such a line?

EDIT: my question specifically refers to the timeout=0. Is there any purpose in using a join with a timeout=0? It is my understanding that a join purpose it to wait, therefore using a timeout=0 seems a little contradictory.

user1315621
  • 3,044
  • 9
  • 42
  • 86
  • Does this answer your question? [Understanding thread.join(timeout)](https://stackoverflow.com/questions/24855335/understanding-thread-jointimeout) – Jacob Lee Mar 26 '21 at 19:33

2 Answers2

0

Timeout basically means the time when the join thread will end. Therefore, a thread.join(timeout=0.0) will end in 0 seconds. However, a thread.join(timeout=1.0) will run for one second, before closing. Now, if the thread is still running after the timeout expires, the join call ends, but the thread keeps running.

As for .join() it is what causes the main thread to wait for your thread to finish. Otherwise, your thread runs all by itself.

So one way to think of .join() as a "hold" on the main thread -- it sort of de-threads your thread and executes sequentially in the main thread, before the main thread can continue. It assures that your thread is complete before the main thread moves forward. Note that this means it's ok if your thread is already finished before you call the .join() -- the main thread is simply released immediately when .join() is called.

The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24
0

The threading documentation explains it well:

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

In essence, the timeout argument tells join() how long to wait for the thread to finish. If the length of time dictated by timeout expires, the join() call will end, but the thread will continue running. That is why you would need to call is_alive() to check if the thread is still running.

Setting the timeout argument to 0.0 would wait 0.0 seconds before timing out, thus, it would time out immediately. So to answer your question, no, there really would be no purpose for calling join() and passing 0.0, as there would be no wait.

Jacob Lee
  • 4,405
  • 2
  • 16
  • 37