Thread join 有点困惑

2019-08-30 03:02:11 +08:00
 lbfeng
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    |---------------------*
2351 次点击
所在节点    Python
9 条回复
nifury
2019-08-30 04:31:41 +08:00
有意义的吧,不记得 join 会不会做 cleanup,但至少如果线程先结束,再 join 的话,join 会直接返回
wd
2019-08-30 06:28:59 +08:00
tread 是自己单独运行的 和你 join 不 join 没关系啊 join 不过是明确表示下后面的语句需要等那个 tread 完毕之后再执行
leishi1313
2019-08-30 06:39:49 +08:00
你不 join main thread 不就直接退出了嘛,除非你 main thread 还需要 t1 t5 的结果,不然不 join 也可以的
frostming
2019-08-30 07:59:17 +08:00
thread 运行当然有可能在 join 之前结束啊

join 只是确保线程结束,若结束则立即返回,否则等待,以及必要的 cleanup.
Vegetable
2019-08-30 09:52:46 +08:00
歪个楼,join 为什么不叫 wait 呢
dinjufen
2019-08-30 09:57:55 +08:00
@Vegetable 这两个两个好像有区别
Vegetable
2019-08-30 10:03:38 +08:00
@Vegetable

> The name join is used because the multiprocessing module's API is meant to look as similar to the threading module's API, and the threading module uses join for its Thread object. Using the term join to mean "wait for a thread to complete" is common across many programming languages, so Python just adopted it as well.
Vegetable
2019-08-30 10:03:49 +08:00
hanssx
2019-09-02 23:40:41 +08:00
正如 4l 所说,t1.join()有意义,t5 所需时间比 t1 长,所以这个代码可以只用 t5.join(),但是实际当中复杂场景你怎么知道哪个线程时间长呢?
另附 join vs. wait 中文区别
线程运行 sleep()或 join()方法后,线程进入 Sleeping 状态。区别在于 sleep 等待固定的时间,而 join 是等待子线程执行完。当然 join 也可以指定一个“超时时间”。从语义上来说,如果两个线程 a、b, 在 a 中调用 b.join(),相当于合并(join)成一个线程。最常见的情况是在主线程中 join 所有的子线程。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/596390

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX