How to wait for a spawned thread to finish in Python

10,410

You can use Thread.join. Few lines from docs.

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

For your example it will be like.

def main():
    a = threading.thread(target = my_thread)
    a.start()
    a.join()
Share:
10,410
Dhruv Patel
Author by

Dhruv Patel

Electrical Engineering Student!

Updated on June 19, 2022

Comments

  • Dhruv Patel
    Dhruv Patel almost 2 years

    I want to use threads to do some blocking work. What should I do to:

    • Spawn a thread safely
    • Do useful work
    • Wait until the thread finishes
    • Continue with the function

    Here is my code:

    import threading
    
    def my_thread(self):
        # Wait for the server to respond..
    
    
    def main():
        a = threading.thread(target=my_thread)
        a.start()
        # Do other stuff here