Puzzle 5 Send It to the Printer

Python Brain Teasers — by Miki Tebeka (14 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 A Task to Do | TOC | Spam, Spam, Spam 👉

printer.py

​1: ​from​ ​threading​ ​import​ Thread
​- ​from​ ​time​ ​import​ sleep
​-
​-
​5: ​def​ ​printer​():
​- ​for​ i ​in​ range(3):
​- ​print​(i, end=​' '​)
​- sleep(0.1)
​-
​10:
​- thr = Thread(target=printer, daemon=True)
​- thr.start()
​- ​print​() ​# Add newline​

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will print: 0

images/hline.png

Output

WARNING

Due to the unpredictable nature of threads, this code might not print anything.

In line 11, you start a daemon thread.

The Python documentation says

The entire Python program exits when no alive non-daemon threads are left.

Since after the print() line there are no more non-daemon threads running, the process will exit. printer…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.