Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 944
Jerry Wu Avatar asked Jul 31 '26 11:07

Jerry Wu


1 Answers

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

Nevertheless, a daemon thread will always be forcefully stopped when the main thread exits, so you either want to use Events or a daemon thread.

Example of using Events:

class BackgroundThread(threading.Thread):

    def __init__(self):
        super().__init__()
        self.shutdown_flag = threading.Event()

    def run(self):
        while not self.shutdown_flag.is_set():
            # Run your code here
            pass

def main_thread():
    # start thread
    bg_thread = BackgroundThread()
    bg_thread.start()

    # do other stuff
    # ...
    
    # Stop your thread
    bg_thread.shutdown_flag.set()
    bg_thread.join()
like image 135
Son Nguyen Avatar answered Aug 02 '26 23:08

Son Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!