我想用线程做一些阻塞的工作。我应该怎么做:
- 安全地生成一个线程
- 做有用的工作
- 等到线程结束
- 继续函数
这是我的代码:
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/