スレッドでの join() の用途は何ですか? 質問する

スレッドでの join() の用途は何ですか? 質問する

私は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()し、削除しても変化は見られません

ベストアンサー1

メカニズムを説明する、やや不格好な ASCII アート: はjoin()、おそらくメイン スレッドによって呼び出されます。別のスレッドによって呼び出される可能性もありますが、図が不必要に複雑になります。

join-calling はメインスレッドのトラックに配置する必要がありますが、スレッド関係を表現し、できるだけシンプルに保つために、代わりに子スレッドに配置することを選択しました。

    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

たとえば、多数のページを同時にダウンロードして 1 つの大きなページに連結したい場合、スレッドを使用して同時ダウンロードを開始できますが、多数のページから 1 つのページを組み立て始める前に、最後のページ/スレッドが終了するまで待つ必要があります。そのときに を使用しますjoin()

おすすめ記事