如何等待生成的线程在Python中完成

时间:2014-09-22 05:16:33

标签: python multithreading thread-safety

我想使用线程来做一些阻塞工作。我该怎么做:

  • 安全地生成一个线程
  • 做有用的工作
  • 等到线程完成
  • 继续使用该功能

这是我的代码:

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 个答案:

答案 0 :(得分:6)

您可以使用Thread.join。来自文档的几行。

  

等到线程终止。这将阻塞调用线程,直到调用join()方法的线程终止 - 正常或通过未处理的异常 - 或直到可选的超时发生。

对于你的例子,它就像是。

def main():
    a = threading.thread(target = my_thread)
    a.start()
    a.join()