zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    如何用最小的代价完成爬虫需求
    那些年我们一起守护的“密”
    自动化中间人攻击工具subterfuge小实验
    XP操作系统设置:[82]关机快捷键
    如何绕过Win8、Win10的systemsetting与注册表校验设置默认浏览器
    定时启动和关闭指定程序的方法
    Delphi 的内存操作函数(2): 给数组指针分配内存
    Delphi 的内存操作函数(1): 给字符指针分配内存
    Java Gearman Service
    分布式计算框架Gearman原理详解
  • 原文地址:https://www.cnblogs.com/uncle-kay/p/9607126.html
Copyright © 2011-2022 走看看