简体   繁体   中英

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM