我想从我的python代码中将一个程序的两个实例作为不同的线程运行。在他们两个都完成之后,我还要做一些其他的事情。
让我们说我有这样的代码:
import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting ", name)
time.sleep(2)
logging.info("Thread %s: finishing ", name)
def main():
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
logging.info("Main: before creating thread")
x = threading.Thread(target=thread_function, args=(1,))
logging.info("Main: before running thread")
x.start()
logging.info("Main: wait for the thread to finish")
logging.info("Main: all done")
if __name__ == "__main__":
main()
此代码在两个线程完成之前打印Main: all done
。但我想等到它们完成后再打印all Done
。有什么解决方法的想法吗?
答案 0 :(得分:1)
您可以使用thread.join()等待线程完成。
import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting ", name)
time.sleep(2)
logging.info("Thread %s: finishing ", name)
def main():
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
logging.info("Main: before creating thread")
x = threading.Thread(target=thread_function, args=(1,))
logging.info("Main: before running thread")
x.start()
logging.info("Main: wait for the thread to finish")
x.join()
logging.info("Main: all done")
if __name__ == "__main__":
main()
答案 1 :(得分:1)
等待直到线程终止。这将阻塞调用线程,直到 调用join()方法的线程终止–通常是 或通过未处理的异常-或直到可选超时 发生。