1

How do I close/exit a thread or daemon thread? I have something like this in my application:

th = ThreadClass(param)
th.daemon = True

if option == 'yes':
    th.start()
elif option == 'no':
    # Close the daemon thread

How do I exit the application?

bulkmoustache
  • 1,875
  • 3
  • 20
  • 24
  • 1
    I'm not sure what you mean. In the `elif` branch of the if statement you have, the thread would never have been started, so there's no need to "close" it. – alecbz May 09 '14 at 20:14
  • @alecb but let's say the first time I run the application, the `option` as the value "yes". And the second time I run it, I set the `option` to "no". – bulkmoustache May 09 '14 at 20:21
  • If the thread is a daemon thread, then `sys.exit(0)` would cause it to close. All daemon threads _should_ be stopped when the last non-daemon thread exits. – g.d.d.c May 09 '14 at 20:22
  • 1
    @vgo I think you may be confused on what daemon threads do -- they are not "persistent" over multiple invocations of the python program or anything like that. They are just threads that do not keep the program alive if all other (non-daemon) threads are done. – alecbz May 09 '14 at 20:24
  • @alecb Then, what if I just start it as a normal thread (`th.daemon=False`)? How could I stop the thread? – bulkmoustache May 09 '14 at 20:29
  • 1
    Note that once again, your program will only end when all threads are dead -- threads don't carry over from one execution to another. However, one way you can close a non-daemon thread is with `th.join()`, which will wait for the thread's function to return. – alecbz May 09 '14 at 20:33

1 Answers1

1

Exit the application by having a "die now" flag. When the parent (or anyone) sets the flag, then all threads watching it will exit.

Example:

import time
from threading import *

class WorkerThread(Thread):
    def __init__(self, die_flag, *args, **kw):
        super(WorkerThread,self).__init__(*args, **kw)
        self.die_flag = die_flag

    def run(self):
        for num in range(3):
            if self.die_flag.is_set():
                print "{}: bye".format(
                    current_thread().name
                    )
                return
            print "{}: num={}".format(
                current_thread().name, num,
                )
            time.sleep(1)

flag = Event()

WorkerThread(name='whiskey', die_flag=flag).start()
time.sleep(2)

print '\nTELL WORKERS TO DIE'
flag.set()

print '\nWAITING FOR WORKERS'
for thread in enumerate():
    if thread != current_thread():
        print thread.name,
        thread.join()
    print
johntellsall
  • 14,394
  • 4
  • 46
  • 40