【问题标题】:How to wait for a spawned thread to finish in Python如何在 Python 中等待生成的线程完成
【发布时间】:2014-09-22 05:16:32
【问题描述】:

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

  • 安全地生成线程
  • 做有用的工作
  • 等到线程结束
  • 继续函数

这是我的代码:

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

【问题讨论】:

    标签: python multithreading thread-safety


    【解决方案1】:

    您可以使用Thread.join。文档中的几行代码。

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

    对于你的例子,它会是这样的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 2018-05-28
      • 2010-12-07
      • 1970-01-01
      相关资源
      最近更新 更多