{"id":7213,"date":"2020-07-21T15:21:26","date_gmt":"2020-07-21T15:21:26","guid":{"rendered":"https:\/\/www.askpython.com\/?p=7213"},"modified":"2022-08-06T13:14:59","modified_gmt":"2022-08-06T13:14:59","slug":"daemon-threads-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/daemon-threads-in-python","title":{"rendered":"Daemon Threads in Python &#8211; What Are They and How to Create Them?"},"content":{"rendered":"\n<p>Hello everyone! In today&#8217;s post, we&#8217;ll be looking at using Daemon Threads in Python. Before we start off with the main topic, let us look at what a Daemon Thread is first!<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Daemon Threads<\/h2>\n\n\n\n<p>A <em>Daemon Thread<\/em> is a type of thread that can run independently in the background. These kinds of threads execute independently of the main thread. So these are called non-blocking threads.<\/p>\n\n\n\n<p><strong>When might you need Daemon threads in Python?<\/strong><\/p>\n\n\n\n<p>Suppose you need to have a long running task which tries to read log files. This task must alert the user when it detects an error message in the logs.<\/p>\n\n\n\n<p>We can assign a daemon thread for this task, which can keep monitoring our log files, while our main program does it&#8217;s usual work!<\/p>\n\n\n\n<p>The best part about daemon threads is that they will automatically stop the execution once the main program finishes!<\/p>\n\n\n\n<p>In case you need a short task, a daemon thread will stop execution after it returns. However, due to this nature, daemon threads are extensively used for long-running background tasks.<\/p>\n\n\n\n<p>Now, let&#8217;s look at an example which shows how we can use them in Python!<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Using Daemon Threads in Python &#8211; A Hands-On Implementation<\/h2>\n\n\n\n<p>These examples in Python will use the <a href=\"https:\/\/www.askpython.com\/python-modules\/multithreading-in-python\" class=\"rank-math-link\">threading module in Python<\/a>, which is part of the standard library.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nimport threading\n<\/pre><\/div>\n\n\n<p>To illustrate the power of daemon threads, let&#8217;s first create two threads, A and B.<\/p>\n\n\n\n<p>We&#8217;ll make <strong>thread A<\/strong> perform a short computation, while <strong>thread B<\/strong> tries to monitor a shared resource.<\/p>\n\n\n\n<p>If this resource is set to <code>True<\/code>, we&#8217;ll make thread B alert the user about the status.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport threading\nimport time\n\n# Set the resource to False initially\nshared_resource = False \n # A lock for the shared resource\nlock = threading.Lock()\n\ndef perform_computation():\n    \n    # Thread A will call this function and manipulate the resource\n    print(f&#039;Thread {threading.currentThread().name} - performing some computation....&#039;)\n    shared_resource = True\n    print(f&#039;Thread {threading.currentThread().name} - set shared_resource to True!&#039;)\n    print(f&#039;Thread {threading.currentThread().name} - Finished!&#039;)\n    time.sleep(1)\n\ndef monitor_resource():\n    # Thread B will monitor the shared resource\n    while shared_resource == False:\n        time.sleep(1)\n    print(f&#039;Thread {threading.currentThread().name} - Detected shared_resource = False&#039;)\n    time.sleep(1)\n    print(f&#039;Thread {threading.currentThread().name} - Finished!&#039;)\n\n\nif __name__ == &#039;__main__&#039;:\n    a = threading.Thread(target=perform_computation, name=&#039;A&#039;)\n    b = threading.Thread(target=monitor_resource, name=&#039;B&#039;)\n\n    # Now start both threads\n    a.start()\n    b.start()\n<\/pre><\/div>\n\n\n<p>Here, <strong>Thread A<\/strong> will set <code>shared_resource<\/code> to <code>True<\/code>, and <strong>thread B<\/strong> will wait for this resource to be True.<\/p>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nThread A - performing some computation....\nThread A - set shared_resource to True!\nThread A - Finished!\nThread B - Detected shared_resource = False\nThread B - Finished!\n<\/pre><\/div>\n\n\n<p>Notice that both threads are normal threads. Now let&#8217;s make thread B to be a daemon thread. Let&#8217;s see what happens now.<\/p>\n\n\n\n<p>To do this, we can set it as a parameter in the <code>threading.Thread(daemon=True)<\/code> method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport threading\nimport time\n\nshared_resource = False # Set the resource to False initially\nlock = threading.Lock() # A lock for the shared resource\n\ndef perform_computation():\n    # Thread A will call this function and manipulate the resource\n    print(f&#039;Thread {threading.currentThread().name} - performing some computation....&#039;)\n    shared_resource = True\n    print(f&#039;Thread {threading.currentThread().name} - set shared_resource to True!&#039;)\n    print(f&#039;Thread {threading.currentThread().name} - Finished!&#039;)\n    time.sleep(1)\n\ndef monitor_resource():\n    # Thread B will monitor the shared resource\n    while shared_resource == False:\n        time.sleep(1)\n    print(f&#039;Daemon Thread {threading.currentThread().name} - Detected shared_resource = False&#039;)\n    time.sleep(1)\n    print(f&#039;Daemon Thread {threading.currentThread().name} - Finished!&#039;)\n\n\nif __name__ == &#039;__main__&#039;:\n    a = threading.Thread(target=perform_computation, name=&#039;A&#039;)\n    b = threading.Thread(target=monitor_resource, name=&#039;B&#039;, daemon=True) # Make thread B as a daemon thread\n\n    # Now start both threads\n    a.start()\n    b.start()\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nThread A - performing some computation....\nThread A - set shared_resource to True!\nThread A - Finished!\nDaemon Thread B - Detected shared_resource = False\n<\/pre><\/div>\n\n\n<p>Here, notice that the daemon thread does not finish. This is because it will automatically get killed by the main thread.<\/p>\n\n\n\n<p>The non-blocking nature of daemon threads make it very useful for a lot of Python applications.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned about how we can use Daemon Threads in our Python application<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Python Threading Module <a href=\"https:\/\/docs.python.org\/3\/library\/threading.html\" target=\"_blank\" rel=\"noopener\">Documentation<\/a><\/li><li>JournalDev article on Daemon Threads in Python<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n","protected":false},"excerpt":{"rendered":"<p>Hello everyone! In today&#8217;s post, we&#8217;ll be looking at using Daemon Threads in Python. Before we start off with the main topic, let us look at what a Daemon Thread is first! Daemon Threads A Daemon Thread is a type of thread that can run independently in the background. These kinds of threads execute independently [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":7216,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-7213","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/7213","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=7213"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/7213\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/7216"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=7213"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=7213"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=7213"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}