zoukankan      html  css  js  c++  java
  • 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都无关紧要.

  • 相关阅读:
    面试1
    初级算法-数组1
    程序员常用单词
    SpringBoot
    JDBC
    animate.css 实现 网页滚动指定位置添加动画
    解决打包上线缓存问题
    组件之间双向绑定
    按照给定数组排序原数组
    扩展运算符... 的使用
  • 原文地址:https://www.cnblogs.com/agichen/p/10345270.html
Copyright © 2011-2022 走看看