python thread的join与setDeamon

join


t.start()
t.join()

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method called terminates -- either normally or through an unhandled or until the optional timeout occurs.

将子线程join之后,主线程会等待这些join的子线程结束之后才结束.

join会阻塞


for tid in range(2):
    t = threading.Thread(target=my_counter)
    t.start()
    t.join()

上面这段代码其实不该算是多线程.从上面引用的原文描述就说过: Wait until the thread terminates.

上面的代码当执行到join的时候,程序就阻塞住了...,它在等待当前这个子线程执行完成之后才开始下一个循环,开始start下一个子线程.这是顺序执行的.

正确使用join的方式


thread_array = {}
for tid in range(2):
    t = threading.Thread(target=my_counter)
    t.start()
    thread_array[tid] = t
for i in range(2):
    thread_array[i].join()

要让所有的t.start()调用之后再去join它们.

setDeamon

setDeamon设置为True之后,主线程退出,主线程的所有子线程都会被迫退出.

setDeamon设置为False之后,主线程退出,主线程的所有子线程依然可以继续运行.

setDeamon必须在线程start之前设置.

有join的情况下,主线程会等待它的子线程完成之后再退出,自然setDeamon设置成True或者False都无关紧要.

posted @ 2019-02-01 11:37  agichen  阅读(225)  评论(0编辑  收藏  举报