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

  • 相关阅读:
    怎样去掉a标签的蓝框
    textarea中的内容的获取
    移动端rem布局
    Array的push与unshift方法性能比较分析
    浅谈移动前端性能优化(转)
    移动端高清、多屏适配方案 (转)
    js关于事件的一些总结(系列一)
    移动端实用的meta标签
    浅析js绑定同一个事件依次触发问题系列(一)
    关于移动端input框 在微信中 和ios中无法输入文字的问题
  • 原文地址:https://www.cnblogs.com/jhc888007/p/11359269.html
Copyright © 2011-2022 走看看