Search code examples
pythonmultithreadingdaemon

How to exit python deamon thread gracefully


I have code like below

def run():
  While True:
    doSomething()
def main():
  thread = threading.thread(target = run)
  thread.setDaemon(True)
  thread.start() 
  doSomethingElse()

if I Write code like above, when the main thread exits, the Deamon thread will exit, but maybe still in the process of doSomething.

The main function will be called outside, I am not allowed to use join in the main thread, is there any way I can do to make the Daemon thread exit gracefully upon the main thread completion.


Solution

  • You can use thread threading.Event to signal child thread when to exit from main thread.

    Example:

    class DemonThead(threading.Thread):
    
        def __init__(self):
            self.shutdown_flag = threading.Event()
    
        def run(self):
            while not self.shutdown_flag:
                # Run your code here
                pass
    
    def main_thread():
        demon_thread = DemonThead()
        demon_thread.setDaemon(True) 
        demon_thread.start()
        
        # Stop your thread
        demon_thread.shutdown_flag.set()
        demon_thread.join()