1

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

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
bcsta
  • 1,963
  • 3
  • 22
  • 61
  • Possible duplicate of [time.sleep(x) not working as it should?](https://stackoverflow.com/questions/21886233/time-sleepx-not-working-as-it-should) – Sabrina Nov 05 '18 at 12:17
  • Remove the `thread.daemon = True`. Your program exits before the sleep finishes. – Aran-Fey Nov 05 '18 at 12:19
  • 1
    @Mehdico it has nothing to do with the print statement and buffering. – bcsta Nov 05 '18 at 12:22
  • @Aran-Fey that worked. Thanks! your comment is a solution. – bcsta Nov 05 '18 at 12:22
  • @jfs I'm sure we have plenty of similar questions already, I just can't be bothered to find a duplicate... – Aran-Fey Nov 05 '18 at 12:31
  • @Aran-Fey similar questions have been asked yes but the solutions are different. This should not be marked as a duplicated just becuase it has a similar title to others – bcsta Nov 05 '18 at 12:33
  • @user7331538 Being a knowledge repository and having high-quality Q&A were SO's founding goals AFAIK. – Aran-Fey Nov 05 '18 at 12:45
  • Things evolve don't they? at the same time I still see this platform as a high- quality Q&A. no one else answered my question anyways. – bcsta Nov 05 '18 at 12:47

1 Answers1

2

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().
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149