Linus
Linus

Reputation: 4783

Why does main thread wait for background threads to finish

Given the following code:

from threading import Thread

def dosomething():
    for _ in range(100):
        print("background thread running")


t = Thread(target=dosomething)
t.start()

The program runs as long as the background thread needs to completely go through the loop. My question is, why does the main thread wait for the background thread to finish and doesn't exit immediately after starting the background thread.

Upvotes: 0

Views: 1422

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27125

Because that's the way it ought to be!

Back in the days before multi-threading, a program would end when its main routine ended which also, coincidentally, was when its last (and only) thread ended. When multi-threading became a thing, some languages (e.g., Python, Java) generalized the classic behavior to "program ends when last thread ends," while others (e.g., C/C++) generaized it to "program ends when its main thread ends."

Having worked in both worlds, It's my strong opinion that Python and Java got it right. The main thread is special to the extent that it's the first: It's the one that calls the program's designated entry point. But after things get going, there is no good reason why the main thread should be treated any differently from any other thread. That only complicates things---makes the behavior that much more difficult to explain.

Upvotes: 2

PyPingu
PyPingu

Reputation: 1747

Because that's the way it is. From the threading docs:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument.

I assume that you ran something like python my_script.py on the command line and wondered why it doesn't return you to a prompt until the worker thread is done?

Well if you change your code to:

from threading import Thread

def dosomething():
    for _ in range(100):
        print("background thread running")


t = Thread(target=dosomething, daemon=True)
t.start()

You will find that you are returned to the terminal. However your daemon thread will also die (again from the docs):

Note Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

This is because killing the program means killing the process and since that worker thread is handled by that process it dies - try this article for a fuller explanation on that.

Upvotes: 2

Related Questions