Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a spawned thread to finish in Python

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
like image 511
Dhruv Patel Avatar asked Mar 18 '23 10:03

Dhruv Patel


1 Answers

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()
like image 111
Nilesh Avatar answered Mar 21 '23 14:03

Nilesh