Wait for thread to finish before closing program

5

I have a loop while that ends only when I press the q key, then the program quits. Within this loop , at a certain time or condition, I start a thread that takes a few 10 seconds to execute.

My problem is, if I exit the loop by pressing q with a running thread , it is canceled.

I would like the loop / script to wait for the thread to run, and then end the program. Is that possible?

Thank you.

    
asked by anonymous 26.03.2015 / 16:02

1 answer

2

In addition to the 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, it tells the thread to wait for a given thread to finish before the main thread proceeds and executes the next statement. Here is 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

    
31.03.2015 / 17:14