I have code like below
def run():
While True:
doSomething()
def main():
thread = threading.thread(target = run)
thread.setDaemon(True)
thread.start()
doSomethingElse()
if I Write code like above, when the main thread exits, the Deamon thread will exit, but maybe still in the process of doSomething
.
The main function will be called outside, I am not allowed to use join
in the main thread,
is there any way I can do to make the Daemon thread exit gracefully upon the main thread completion.
You can use thread threading.Event
to signal child thread when to exit from main thread.
Nevertheless, a daemon thread will always be forcefully stopped when the main thread exits, so you either want to use Events or a daemon thread.
Example of using Events:
class BackgroundThread(threading.Thread):
def __init__(self):
super().__init__()
self.shutdown_flag = threading.Event()
def run(self):
while not self.shutdown_flag.is_set():
# Run your code here
pass
def main_thread():
# start thread
bg_thread = BackgroundThread()
bg_thread.start()
# do other stuff
# ...
# Stop your thread
bg_thread.shutdown_flag.set()
bg_thread.join()