Wait to finish the thread before ending the program

Asked

Viewed 1,502 times

5

I have a loop while that ends only when I press the key q, then the program is closed. Within that loop, at a given time or condition, I initiate a thread that takes about a few 10 seconds to run.

My problem is, if I get out of loop squeezing q with a thread running, this is canceled.

I would like the loop/script awaited the execution of the thread, and then finalize the program. This is possible?

Thank you.

  • Dude, could you put in the relevant part of your code? I think it’s kind of abstract with nothing in the code...

  • But possibly using a thread.isAlive() solve your problem...

  • @Felipeavelar, thanks for the feedback. I can even use the.isAlive() thread to detect if it exists, but how to "wait" for the thread to close? Ah, another thing, I realized that even if I shut down the program and went back to the prompt, the thread keeps running until it’s finished, in a way that’s good, I just wanted it to wait to get back to the prompt.

  • Could put a while thread.isAlive(): pass. But I can’t say with precision, without seeing the code.

1 answer

2


In addition to the mode mentioned by Felipe Avelar using the method Thread.is_alive(), there is also the method Thread.join(). Both can be used together.

When Thread.join() is called, says the thread main to expect a particular thread end, before the thread main proceed and execute the next instruction. Follow an example:

import time, threading

def fun():
    for i in range(5):
        time.sleep(1)
        print(i)

def main():
    thread = threading.Thread(target=fun)
    thread.start()
    thread.join()
    # A thread foi finalizada, fazer algo a partir daqui
    print("Thread finalizada")

main()

DEMO

Browser other questions tagged

You are not signed in. Login or sign up in order to post.