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

  • 相关阅读:
    将图片保存到数据库中及转换
    svn 插件地址
    反射
    android 使用Sax 读取xml
    抓取 网页信息
    客户端测试
    简单多线程+委托+事件
    postman实战四
    Postman练习
    Jmeter练习二添加书籍信息
  • 原文地址:https://www.cnblogs.com/jhc888007/p/11359269.html
Copyright © 2011-2022 走看看