Movatterモバイル変換


[0]ホーム

URL:


Daemon Threads in Python

Learn what daemon threads are with toy examples as well as real world examples and how to set daemon threads in Python
  · 4 min read · Updated jan 2021 ·Python Standard Library

Welcome! Meet ourPython Code Assistant, your new coding buddy. Why wait? Start exploring now!

In this tutorial, you will learn what are daemon threads in Python and how to set them up, you should have a basic knowledge about threads to follow up in this tutorial.

A daemon thread is a thread that dies whenever the main thread dies, it is also called a non-blocking thread. Usually, the main thread should wait for other threads to finish in order to quit the program, but if you set the daemon flag, you can let the thread do its work and forget about it, and when the program quits, it will be killed automatically.

This is useful for many scenarios, suppose you are doing someweb scraping tasks, and you want to make a thread that alerts you in email whenever a new item is inserted in that particular website you're scraping.

Another example you may want to make a thread that watches for log files in your program, and alert you when a critical error is occured.

In the end of the tutorial, we'll share with you some tutorials that we found useful to use daemon threads in.

Now that you know what a daemon thread is, and you know it's useful, let's take a demonstration example, the following code initiates a non-daemon thread and start it, and then we end the main thread as well:

import threadingimport timedef func():    while True:        print(f"[{threading.current_thread().name}] Printing this message every 2 seconds")        time.sleep(2)# initiate the thread to call the above functionnormal_thread = threading.Thread(target=func, name="normal_thread")# start the threadnormal_thread.start()# sleep for 4 seconds and end the main threadtime.sleep(4)# the main thread ends

Thefunc() function should run forever, as we're settingTrue as the condition of thewhile loop. After we started that thread, we make a simple sleep in the main thread and exit the program.

However, if you run it, you'll see the program keeps running and won't allow you to exit (only if you close the window):

[normal_thread] Printing this message every 2 seconds[normal_thread] Printing this message every 2 seconds[normal_thread] Printing this message every 2 seconds[normal_thread] Printing this message every 2 seconds[normal_thread] Printing this message every 2 seconds...goes forever

So the non-daemon thread is making the program refuses to exit until it's finished.

The following example initiates a daemon thread this time:

import threadingimport timedef func_1():    while True:        print(f"[{threading.current_thread().name}] Printing this message every 2 seconds")        time.sleep(2)# initiate the thread with daemon set to Truedaemon_thread = threading.Thread(target=func_1, name="daemon-thread", daemon=True)# or# daemon_thread.daemon = True# or# daemon_thread.setDaemon(True)daemon_thread.start()# sleep for 10 seconds and end the main threadtime.sleep(4)# the main thread ends

Now we passdaemon=True tothreading.Thread class to indicate that it's a daemon thread, you can also access thedaemon attribute toTrue or use thesetDaemon(True) method.

Let's execute the program:

[daemon-thread] Printing this message every 2 seconds[daemon-thread] Printing this message every 2 seconds

This time once the main thread finishes its work, the daemon thread also gets killed automatically and exits the program.

Real Examples

Below are some of the tutorials in which we used daemon threads to accomplish our tasks:

Happy coding ♥

Take the stress out of learning Python. Meet ourPython Code Assistant – your new coding buddy. Give it a whirl!

View Full Code Generate Python Code
Sharing is caring!



Read Also


How to Use Threads for IO Tasks in Python
Logging in Python
How to Build a WiFi Scanner in Python using Scapy

Comment panel

    Got a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!





    Ethical Hacking with Python EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Ethical Hacking with Python EBook - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Ethical hacking with Python from Scratch Chapter.

    See how the book can help you build awesome hacking tools with Python!



    [8]ページ先頭

    ©2009-2025 Movatter.jp