What happens if I don't join() a python thread?

Question:

I have a query. I have seen examples where developers write something like the code as follows:

import threading
def do_something():
    return true
t = threading.Thread(target=do_something)
t.start()
t.join()

I know that join() signals the interpreter to wait till the thread is completely executed. But what if I do not write t.join()? Will the thread get closed automatically and will it be reused later?
Please let me know the answer. It’s my first attempt at creating a multi-threaded application in Python 3.5.0.

Asked By: Jaffer Wilson

||

Answers:

The join part means the main program will wait for the thread to end before continuing. Without join, the main program will end and the thread will continue.

Now if you set the daemon parameter to “True”, it means the thread will depends on the main program, and it will ends if the main program ends before.

Here is an example to understand better :

import threading
import time

def do_something():
    time.sleep(2)
    print("do_something")
    return True

t = threading.Thread(target=do_something)
t.daemon = True # without the daemon parameter, the function in parallel will continue even your main program ends
t.start()
t.join() # with this, the main program will wait until the thread ends
print("end of main program")

no daemon, no join:

end of main program
do_something

daemon only:

end of main program

join only:

do_something
end of main program

daemon and join:

do_something
end of main program
# Note : in this case the daemon parameter is useless
Answered By: Phoenixo

A Python thread is just a regular OS thread. If you don’t join it, it still keeps running concurrently with the current thread. It will eventually die, when the target function completes or raises an exception. No such thing as “thread reuse” exists, once it’s dead it rests in peace.

Unless the thread is a “daemon thread” (via a constructor argument daemon or assigning the daemon property) it will be implicitly joined for before the program exits, otherwise, it is killed abruptly.

One thing to remember when writing multithreading programs in Python, is that they only have limited use due to infamous Global interpreter lock. In short, using threads won’t make your CPU-intensive program any faster. They can be useful only when you perform something involving waiting (e.g. you wait for certain file system event to happen in a thread).

Answered By: bereal
  • Without join(), non-daemon threads are running and are completed with the main thread concurrently.

  • Without join(), daemon threads are running with the main thread concurrently and when the main thread is completed, the daemon threads are exited without completed if the daemon threads are still running.

You can see my answer in this post explaining about it in detail.

Answered By: Kai – Kazuya Ito