• Daemon 守护线程(27-11)


    t2.setDaemon(True)不再等待里面的sleep(5)。

    当设成setDaemon(True)这个线程就不等了。

      例子一:

    import threading
    from time import ctime, sleep

    def music(func):
      for i in range(2):
        print(func, ctime())      # 1 执行  # 5 执行
        sleep(1)
        print("end music", ctime())  # 4 执行  # 6 执行

    def move(func):
      for i in range(2):
        print(func, ctime())      # 2 执行
        sleep(5)
        print("end move", ctime())

     threads = []

     t1 = threading.Thread(target=music,args=("小苹果",))

      threads.append(t1)

      t2 = threading.Thread(target=move,args=("华尔街之狼",))

      threads.append(t2)

      if __name__ == "__main__":

        t2.setDaemon(True)

        for t in threads:

          t.start()

        print("程序执行结束", ctime())    # 3 执行

    程序运行结果:

    小苹果 Fri Sep  7 20:04:24 2018
    华尔街之狼 Fri Sep  7 20:04:24 2018
    程序执行结束 Fri Sep  7 20:04:24 2018
    end music Fri Sep  7 20:04:25 2018
    小苹果 Fri Sep  7 20:04:25 2018
    end music Fri Sep  7 20:04:26 2018
    

      ------------------------------------------------------------------------------------------------------

      例子二:

    t.setDaemon(True)谁也不等待
    import threading
    from time import ctime, sleep
    
    def music(func):
      for i in range(2):
        print(func, ctime())      # 1 执行  
        sleep(1)
        print("end music", ctime())  
    
    def move(func):
      for i in range(2):
        print(func, ctime())      # 2 执行
        sleep(5)
        print("end move", ctime())
     threads = []
    
     t1 = threading.Thread(target=music,args=("小苹果",))
    
      threads.append(t1)
    
      t2 = threading.Thread(target=move,args=("华尔街之狼",))
    
      threads.append(t2)
    
      if __name__ == "__main__":
        for t in threads:
          t.setDaemon(True)
          t.start()
        print("程序执行结束", ctime())    # 3 执行

    程序运行结果:

    小苹果 Fri Sep 7 20:18:31 2018
    华尔街之狼 Fri Sep 7 20:18:31 2018
    程序执行结束 Fri Sep 7 20:18:31 2018

  • 相关阅读:
    seo 优化 仅针对 来拍呀www.laipaiya.com(一)
    mac 下 配置 xhprof
    mac 下 sphinx + mysql + php 实现全文搜索(xampp)(4)php api 解析
    mac 下 sphinx + mysql + php 实现全文搜索(xampp)(3)sphinx 的配置项解析
    php + mysql + sphinx 的全文检索(2)
    mac 下 sphinx + mysql + php 实现全文搜索(xampp)(1)
    mysql 的 存储结构(储存引擎)
    [php] yii debug设置
    [mysql] 查看mysql执行时间
    [javascript] 对象拷贝
  • 原文地址:https://www.cnblogs.com/uncle-kay/p/9607126.html
Copyright © 2020-2023  润新知