• 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

  • 相关阅读:
    selenium-03-01截图函数
    selenium-03-02操作元素-等待
    [转]Linux下 tar.xz格式文件的解压方法
    selenium-05-问题2
    selenium-05-常见问题
    selenium-01-简介
    underscore
    前端底层-继承
    前端底层-面向对象3
    前端底层-面向对象2
  • 原文地址:https://www.cnblogs.com/jhc888007/p/11359269.html
Copyright © 2020-2023  润新知