开发者社区> 问答> 正文

如何同时运行两个线程并等待结果

我想从我的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。应该如何解决?

展开
收起
安忆333 2019-12-03 19:36:56 953 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()
    
    2019-12-03 19:37:36
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
多IO线程优化版 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多