我想从我的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。应该如何解决?
你可以使用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()
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。