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 |---------------------*
1
nifury 2019-08-30 04:31:41 +08:00
有意义的吧,不记得 join 会不会做 cleanup,但至少如果线程先结束,再 join 的话,join 会直接返回
|
2
wd 2019-08-30 06:28:59 +08:00 via iPhone
tread 是自己单独运行的 和你 join 不 join 没关系啊 join 不过是明确表示下后面的语句需要等那个 tread 完毕之后再执行
|
3
leishi1313 2019-08-30 06:39:49 +08:00
你不 join main thread 不就直接退出了嘛,除非你 main thread 还需要 t1 t5 的结果,不然不 join 也可以的
|
4
frostming 2019-08-30 07:59:17 +08:00
thread 运行当然有可能在 join 之前结束啊
join 只是确保线程结束,若结束则立即返回,否则等待,以及必要的 cleanup. |
5
Vegetable 2019-08-30 09:52:46 +08:00
歪个楼,join 为什么不叫 wait 呢
|
7
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. |
8
Vegetable 2019-08-30 10:03:49 +08:00
|
9
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 所有的子线程。 |