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

Dhr*_*tel 3 python multithreading thread-safety

我是初学者,在python中使用线程.我需要一些帮助,我应该怎么做: - 产生一个线程 - 做一些有用的工作 - 等到线程完成 - 做一些有用的工作

我不太确定我是否安全地产生了一个线程.也可能需要一些帮助.

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
Run Code Online (Sandbox Code Playgroud)

Nil*_*esh 6

你可以用Thread.join.来自docs的几行.

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

对于你的例子,它就像.

def main():
    a = threading.thread(target = my_thread)
    a.start()
    a.join()
Run Code Online (Sandbox Code Playgroud)