Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!Sometimes, it is necessary to execute a task in the background. A special type of thread is used for background tasks, called a daemon thread. In other words, daemon threads execute tasks in the background.
It may be noted that daemon threads execute such non-critical tasks that although may be useful to the application but do not hamper it if they fail or are canceled mid-operation.
Also, a daemon thread will not have control over when it is terminated. The program will terminate once all non-daemon threads finish, even if there are daemon threads still running at that point of time.
This is a major difference between daemon threads and non-daemon threads. The process will exit if only daemon threads are running, whereas it cannot exit if at least one non-daemon thread is running.
Daemon | Non-daemon |
---|---|
A process will exit if only daemon threads are running (or if no threads are running). | A process will not exit if at least one non-daemon thread is running. |
Creating a Daemon Thread
To create a daemon thread, you need to set the daemon property to True.
If a thread object is created without any parameter, its daemon property can also be set to True, before calling the start() method.
Example
Take a look at the following example −
It will produce the following output −
Daemon thread: True
Daemon threads can perform executing tasks that support non-daemon threads in the program. For example −
-
Create a file that stores Log information in the background.
-
Perform web scraping in the background.
-
Save the data automatically into a database in the background.
Example
If a running thread is configured to be daemon, then a RuntimeError is raised. Take a look at the following example −
It will produce the following output −
Exception in thread Thread-1 (run): Traceback (most recent call last): . . . . . . . . thread.daemon = True ^^^^^^^^^^^^^ File "C:\Python311\Lib\threading.py", line 1219, in daemon raise RuntimeError("cannot set daemon status of active thread") RuntimeError: cannot set daemon status of active thread
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.