Python线程中的join()有什么用?

发布于 2021-01-29 15:00:14

我正在研究python线程并遇到了join()

作者告诉我,如果线程处于守护程序模式,那么我需要使用它,join()以便线程可以在主线程终止之前完成自身。

但我一直在使用也没见他t.join()即使tdaemon

示例代码是这个

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

def daemon():
    logging.debug('Starting')
    time.sleep(2)
    logging.debug('Exiting')

d = threading.Thread(name='daemon', target=daemon)
d.setDaemon(True)

def non_daemon():
    logging.debug('Starting')
    logging.debug('Exiting')

t = threading.Thread(name='non-daemon', target=non_daemon)

d.start()
t.start()

d.join()
t.join()

我不知道这是什么用途,t.join()因为它不是守护程序,即使删除它也看不到任何变化

关注者
0
被浏览
125
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    展示这种机制的技术有些笨拙:join()大概是由主线程调用的。也可以由另一个线程调用它,但是会不必要地使该图复杂化。

    join-调用应该放在主线程的轨道上,但是为了表达线程关系并使它尽可能简单,我选择将其放在子线程中。

    without join:
    +---+---+------------------                     main-thread
        |   |
        |   +...........                            child-thread(short)
        +..................................         child-thread(long)
    
    with join
    +---+---+------------------***********+###      main-thread
        |   |                             |
        |   +...........join()            |         child-thread(short)
        +......................join()......         child-thread(long)
    
    with join and daemon thread
    +-+--+---+------------------***********+###     parent-thread
      |  |   |                             |
      |  |   +...........join()            |        child-thread(short)
      |  +......................join()......        child-thread(long)
      +,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,     child-thread(long + daemonized)
    
    '-' main-thread/parent-thread/main-program execution
    '.' child-thread execution
    '#' optional parent-thread execution after join()-blocked parent-thread could 
        continue
    '*' main-thread 'sleeping' in join-method, waiting for child-thread to finish
    ',' daemonized thread - 'ignores' lifetime of other threads;
        terminates when main-programs exits; is normally meant for 
        join-independent tasks
    

    因此,您看不到任何更改的原因是因为您的主线程在之后没有执行任何操作join。您可以说join(仅)与主线程的执行流相关。

    例如,如果您想同时下载一堆页面以将它们串联成一个大页面,则可以使用线程开始并发下载,但是需要等到最后一页/线程完成后才能开始组装单个页面在很多。那是您使用的时间join()



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看