zoukankan      html  css  js  c++  java
  • Python多线程与多线程中join()的用法

    多线程实例

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

    知识点一:
    当一个进程启动之后,会默认产生一个主线程,因为线程是程序执行流的最小单元,当设置多线程时,主线程会创建多个子线程,在python中,默认情况下(其实就是setDaemon(False)),主线程执行完自己的任务以后,就退出了,此时子线程会继续执行自己的任务,直到自己的任务结束,例子见下面一。

    知识点二:
    当我们使用setDaemon(True)方法,设置子线程为守护线程时,主线程一旦执行结束,则全部线程全部被终止执行,可能出现的情况就是,子线程的任务还没有完全执行结束,就被迫停止,例子见下面二。

    知识点三:
    此时join的作用就凸显出来了,join所完成的工作就是线程同步,即主线程任务结束之后,进入阻塞状态,一直等待其他的子线程执行结束之后,主线程在终止,例子见下面三。

    知识点四:
    join有一个timeout参数:

      1. 当设置守护线程时,含义是主线程对于子线程等待timeout的时间将会杀死该子线程,最后退出程序。所以说,如果有10个子线程,全部的等待时间就是每个timeout的累加和。简单的来说,就是给每个子线程一个timeout的时间,让他去执行,时间一到,不管任务有没有完成,直接杀死。
      2. 没有设置守护线程时,主线程将会等待timeout的累加和这样的一段时间,时间一到,主线程结束,但是并没有杀死子线程,子线程依然可以继续执行,直到子线程全部结束,程序退出。
    #!/usr/bin/env python
    # -*- encoding: utf-8 -*-
    
    
    import threading
    from time import ctime, sleep
    import time
    import requests
    
    i = 1
    
    def music(func, c):
        for i in range(3):
            i += 1
            r = requests.get('http://www.baidu.com')
            print r
            print func, c, time.time()
    
    
    def move(func):
        for i in range(2):
            print "I was at the %s! %s" % (func, ctime())
            # sleep(5)
    
    
    threads = []
    t2 = threading.Thread(target=move, args=(u'阿凡达',))
    threads.append(t2)
    
    t1 = threading.Thread(target=music, args=(u'爱情买卖', '333'))
    threads.append(t1)
    t1 = threading.Thread(target=music, args=(u'爱情买卖', '4444'))
    threads.append(t1)
    t1 = threading.Thread(target=music, args=(u'爱情买卖', '5555'))
    threads.append(t1)
    t1 = threading.Thread(target=music, args=(u'爱情买卖', '6666'))
    threads.append(t1)
    t1 = threading.Thread(target=music, args=(u'爱情买卖', '7777'))
    threads.append(t1)
    t1 = threading.Thread(target=music, args=(u'爱情买卖', '8888'))
    threads.append(t1)
    
    
    
    
    if __name__ == '__main__':
    
        for t in threads:
            t.setDaemon(True)
            t.start()
    
        for t in threads:
            t.join()
    
        print "all over %s" % ctime()
  • 相关阅读:
    又快又准的sql瓶颈诊断方法
    Qps从300到1500的优化过程
    Mysql性能优化全揭秘-庖丁解牛
    java学习笔记16-抽象类
    java学习笔记15-封装
    java学习笔记14-多态
    java学习笔记13-重写与重载
    Git学习笔记08-远程仓库
    Python3+Appium学习笔记09-元素定位android_uiautomator
    Python3+Appium学习笔记08-元素定位
  • 原文地址:https://www.cnblogs.com/zhaoyingjie/p/10190618.html
Copyright © 2011-2022 走看看