Joining a Daemon thread

Viewed 5098

I was reading about daemon threads, and came across this SO page, the comment under the answer says:

But joining a demonized thread opens most likely a whole can of trouble! I'm now considering to remove the join() call in my little diagram for the daemon-thread

I understand what daemon threads are used for and why but, suppose you had to wait for a daemon thread to finish what it's doing, how would you do it if calling join() is considered a lot of trouble?

1 Answers

If you want to be able to .join a thread, it's better to not make it a daemon. Daemon threads are for when you want a thread to do its thing and you're not too concerned about when or if it finishes.

The point of making daemon threads is that the program will exit when there are no non-daemon threads left alive.

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.

You can actually call .join on daemon threads, but it's generally considered to be not good practice.

You could get a daemon thread to set an Event just before it finishes, which one or more other threads check, but it's simpler just to use a non-daemon thread and .join it.

An earlier version of this answer claimed that you can't .join a daemon thread. That's incorrect. I was getting mixed up with dummy threads. Sorry about that. :oops:

Related