zoukankan      html  css  js  c++  java
  • Python 多线程总结

    • 主线程启动多个子线程后,默认情况下(即setDaemon(False)),主线程执行完后即退出,不影响子线程继续执行
    import time
    import threading
    
    def sub_thread(i):
        print("sub_thread begin", i)
        time.sleep(i)
        print("sub_thread end", i)
    
    print("main_thread begin")
    thread_lst = []
    for i in range(1, 5): 
        t = threading.Thread(target = sub_thread, args = (i, ))
        thread_lst.append(t)
    for t in thread_lst:
        t.start()
    time.sleep(1)
    print("main_thread end")
    • 如果设置setDaemon(True),则主线程执行完后,在退出前会杀死所有子进程
    import time
    import threading
    
    def sub_thread(i):
        print("sub_thread begin", i)
        time.sleep(i)
        print("sub_thread end", i)
    
    print("main_thread begin")
    thread_lst = []
    for i in range(1, 5): 
        t = threading.Thread(target = sub_thread, args = (i, ))
        t.setDaemon(True)
        thread_lst.append(t)
    for t in thread_lst:
        t.start()
    time.sleep(1)
    print("main_thread end")
    • 如果加上join,则主进程会在对应位置阻塞等待子线程结束
    import time
    import threading
    
    def sub_thread(i):
        print("sub_thread begin", i)
        time.sleep(i)
        print("sub_thread end", i)
    
    print("main_thread begin")
    thread_lst = []
    for i in range(1, 5): 
        t = threading.Thread(target = sub_thread, args = (i, ))
        t.setDaemon(True)
        thread_lst.append(t)
    for t in thread_lst:
        t.start()
    time.sleep(1)
    for t in thread_lst:
        t.join()
    print("main_thread end")
    • 如果设置timeout,则对应等待语句最多等待timeout秒
    import time
    import threading
    
    def sub_thread(i):
        print("sub_thread begin", i)
        time.sleep(i)
        print("sub_thread end", i)
    
    print("main_thread begin")
    thread_lst = []
    for i in range(1, 5): 
        t = threading.Thread(target = sub_thread, args = (i, ))
        t.setDaemon(True)
        thread_lst.append(t)
    for t in thread_lst:
        t.start()
    time.sleep(1)
    thread_lst[0].join(timeout = 2)
    thread_lst[3].join(timeout = 2)
    print("main_thread end")

    参考文献:

    https://www.cnblogs.com/cnkai/p/7504980.html

  • 相关阅读:
    与MS Project相关的两个项目
    最后的报告bug
    oo第二阶段的总结
    第一阶段的反思和改变
    面向对象设计与构造第四次课程总结
    面向对象设计与构造第三次课程总结
    面向对象设计与构造第一次课程总结
    OO游记之六月篇
    OO游记之五月篇
    OO游记之四月篇
  • 原文地址:https://www.cnblogs.com/jhc888007/p/11359269.html
Copyright © 2011-2022 走看看