Reputation: 2025
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?
Upvotes: 1
Views: 570
Reputation: 15180
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
Upvotes: 1