3

Suppose I have something like this :

import threading
import time

_FINISH = False


def hang():
    while True:
        if _FINISH:
            break
        print 'hanging..'
        time.sleep(10)


def main():
    global _FINISH
    t = threading.Thread(target=hang)
    t.setDaemon( True )
    t.start()
    time.sleep(10)

if __name__ == '__main__':
    main()

If my thread is daemon, do I need to have a global _FINISH to control exit clause of break loop? I tried and I don't seem to need it - when program exits ( in that case after the sleep ) then program terminates, which closes the thread too.

But I've seen that code too - is it just bad practise? Can I get away with no global flag for controlling the loop?

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
ghostrider
  • 5,131
  • 14
  • 72
  • 120

1 Answers1

3

According to [Python 3.Docs]: threading - Thread Objects (emphasis is mine):

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. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument.

Note: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

Per above, technically, you don't need the _FINISH logic, as the thread will end when the main one does.
But, according to your code, no one (main thread) signals that the thread should end (something like _FINISH = True), so the logic in the thread is useless (therefore it can be removed).
Also, according to the above recommendation, you should implement the synchronization mechanism between your threads, and avoid making them daemons (in most of the cases).

Community
  • 1
  • 1
CristiFati
  • 38,250
  • 9
  • 50
  • 87