1

In Python, is there any benefit of making a Thread and then join() over normal blocking process? For example, is this code:

def sleep():
    time.sleep(5)

print "start..."
t = threading.Thread(target=sleep)
t.start()
t.join()
print "end..."

any better than this:

def sleep():
    time.sleep(5)

print "start..."
sleep()
print "end..."

Is there any use-case or situation where one of it is better than the other?

akmalmzamri
  • 1,035
  • 1
  • 15
  • 31
  • None of these two is better because they both make no sense. Please illustrate your question with a real problem. –  Apr 03 '18 at 08:14

1 Answers1

2

In general, if you join on a single thread there is not much benefit over a non-threaded approach.

The only thing I can think of is that you can specify a timeout for join to limit the time a computation may take. This is also possible without threads, but it would require you to modify the target function (to periodically check whether the time limit has been reached). Using a timeout for join is transparent to the underlying function.

Obviously, if you have more than one thread then joining one or more of them is drastically different than a single-threaded program, since the threads then work in parallel while only the main thread waits for the join to complete.

Florian Brucker
  • 9,621
  • 3
  • 48
  • 81
  • 1
    Calling `join(timeout)` will _not_ limit the time that a computation in a background thread may take. It only will limit the amount of time that the calling thread is willing to wait for it. – Solomon Slow Apr 03 '18 at 13:58
  • @jameslarge you are correct and I was sloppy. Thanks for the clarification! After `join(timeout)` returns, one needs to call `is_alive` to check whether the thread is still running and (if it is) stop it -- ideally in a cooperative way [or forcefully](https://stackoverflow.com/q/323972/857390). – Florian Brucker Apr 03 '18 at 18:36