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

Asked By: Matěj Růžička

||

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
Answered By: 0x150
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.