How to wait for a spawned thread to finish in Python

六月ゝ 毕业季﹏ 提交于 2019-12-23 19:28:11

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/25967093/how-to-wait-for-a-spawned-thread-to-finish-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!