How to stop the threads in Python when the main process is at the end?
Question:
I have theards in Python and I need to kill them when the main process is at the end. How can I do that?
MY CODE:
- first thread:
def run():
Log.new_record(record_type="INFO", record_text=f"The webserver has been started. Server is running on port: {port}")
app.run(host="0.0.0.0", port=port, debug=False)
webserver_thread = threading.Thread(target=run, daemon=True)
webserver_thread.start()
- second thread:
def run():
while True:
#do something
thread = threading.Thread(target=run, daemon=True)
thread.start()
I tried the ._stop()
function, but this error occurred. error
Answers:
You can put your thread in a loop and use thread.event
You could set a global flag that indicates that the process should exit, which the thread then reads each tick to check if it should continue. If not, just break
out of the loop, or directly do while not do_exit:
.
do_exit = False
def run():
while not do_exit:
# Do something
# start run thread and do something
do_exit = True
# now just wait for run() to finish
I have theards in Python and I need to kill them when the main process is at the end. How can I do that?
MY CODE:
- first thread:
def run():
Log.new_record(record_type="INFO", record_text=f"The webserver has been started. Server is running on port: {port}")
app.run(host="0.0.0.0", port=port, debug=False)
webserver_thread = threading.Thread(target=run, daemon=True)
webserver_thread.start()
- second thread:
def run():
while True:
#do something
thread = threading.Thread(target=run, daemon=True)
thread.start()
I tried the ._stop()
function, but this error occurred. error
You can put your thread in a loop and use thread.event
You could set a global flag that indicates that the process should exit, which the thread then reads each tick to check if it should continue. If not, just break
out of the loop, or directly do while not do_exit:
.
do_exit = False
def run():
while not do_exit:
# Do something
# start run thread and do something
do_exit = True
# now just wait for run() to finish