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

标签 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

最佳答案

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

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.

以你的例子为例。

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

关于python - 如何等待生成的线程在 Python 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25967093/

相关文章:

java - 如果 Swing 模型的 getter 不是线程安全的,您将如何处理它们?

assembly - 如何使用 LOCK ASM 前缀来读取值?

python - 为什么我的文本文件不断覆盖其中的数据?

c - 测量线程的上下文切换时间

arrays - 计算数组平均值的高效并行调度算法

c++ - 使用多线程的 C++ 中的 Mandelbrot 图像生成器 "overwrites(?)"一半图像

java - 我如何保证线程在终止时安全地解锁锁,而所有方法都已经处理了该锁?

python - 我需要计算 python 中同一位置的类似字符,但我不知道如何正确计算,因为我是该程序的新手

python - Pandas 数据框中的Groupby

java - Python调用Java导致错误: Could not find or load main class