• 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都无关紧要.

  • 相关阅读:
    sql面试题
    C#基础(1)
    Java中的冒泡排序(减少比较次数)
    Java中面向对象的分拣存储
    Java中分拣存储的demo
    XML序列化
    C#读取csv文件使用字符串拼接成XML
    Java中HashMap(泛型嵌套)的遍历
    Java 中List 集合索引遍历与迭代器遍历
    java 中的try catch在文件相关操作的使用
  • 原文地址:https://www.cnblogs.com/agichen/p/10345270.html
Copyright © 2020-2023  润新知