简体   繁体   中英

Program terminates instantly ignoring time.sleep() in a daemon thread

I have a class that is calling a thread like below.

import threading
import time

class ThreadingExample:
    def __init__(self):
        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                           
        thread.start()                                 

    def run(self):

        # Do something
        print('Doing something important in the background')

        time.sleep(100)

        # a print statement will not be executed here even with flush=True

example = ThreadingExample()

However, sleep is not working. The thread is executed since the first print in run() is being printed however the program terminates instantly after the print statement.

For testing purposes I inserted another print statement after the sleep(100) and that does not print either. what is the problem here?

This code should be completed and reproducable

The problem is this line:

thread.daemon = True

From the threading documentation :

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.

Because you've made your thread a daemon thread, python doesn't wait for it to finish before exiting the program. As soon as the main thread is done executing your code, the daemon thread is killed and the program exits.

There are two ways to solve this problem:

  1. Removing the thread.daemon = True assignment so that python will wait for your thread to exit.
  2. Explicitly waiting for the thread to finish by calling thread.join() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM