Search⌘ K

Puzzle 5: Explanation

Explore how daemon threads affect Python program exit behavior by studying a practical example. Understand why a program may exit unexpectedly due to daemon threads and learn how to use the thread join method to wait for threads to finish, improving your threading control and debugging skills.

We'll cover the following...

Let’s try it!

Try executing the code below to verify the result:

Python 3.8
from threading import Thread
from time import sleep
def printer():
for i in range(3):
print(i, end=' ')
sleep(0.1)
thr = Thread(target=printer, daemon=True) # <label id="code.daemon"/>
thr.start()
print() # Add newline

Explanation

In line 11, we start a daemon thread. Here’s what Python ...