import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(name)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
logging.info("Main : before creating thread")
t1 = threading.Thread(target=thread_function, args=(1,))
t5 = threading.Thread(target=thread_function, args=(5,))
logging.info("Main : before running thread")
t1.start()
t5.start()
logging.info("Main : wait for the thread to finish")
t5.join()
print('between 5 & 1')
t1.join()
logging.info("Main : all done")
14:44:51: Main : before creating thread
14:44:51: Main : before running thread
14:44:51: Thread 1: starting
14:44:51: Thread 5: starting
14:44:51: Main : wait for the thread to finish
14:44:52: Thread 1: finishing
14:44:56: Thread 5: finishing
between 5 & 1
14:44:56: Main : all done
显然 t1 比 t5 先结束,t5.join()只能 block main thread,那 t1.join()还有任何意义吗?会不会出现 thread 在 join 之前就结束的情况?
timeline
main -----------------------*
t1 |---*
t5 |---------------------*
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.