简体   繁体   English

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

[英]How to run two threads simultaneously and wait for the result

I would like to run from my python code two instances of one program as different threads.我想从我的 python 代码运行一个程序的两个实例作为不同的线程。 And after both of them finishes I would like to do some other stuff.在他们两个完成后,我想做一些其他的事情。

Lets say I have code like that:假设我有这样的代码:

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()

This code prints Main: all done before the two threads finish.此代码打印Main: all done之前两个线程完成。 But I would like to wait until they are finished and than print all Done .但我想等到它们完成all Done打印all Done Any ideas how to solve it?任何想法如何解决它?

You can use thread.join() to wait for a Thread to finish.您可以使用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()

join(timeout=None)¶ 加入(超时=无)¶

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.这会阻塞调用线程,直到调用其 join() 方法的线程终止 - 正常或通过未处理的异常 - 或者直到发生可选超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM