多线程 -- threading

  • 多线程的调用
    • 直接调用
      import threading
      import time
      
      #定义每个线程要运行的函数
      def my_func(num, **kwargs):
      
          print("%s running on number:%s" % (kwargs['name'], num))
          time.sleep(3)
      
      if __name__ == '__main__':
          #生成一个线程实例
          t1 = threading.Thread(target=my_func, args=(1,), kwargs={'name': 'my_thread'})
          #生成另一个线程实例
          t2 = threading.Thread(target=my_func, args=(2,), kwargs={'name': 'my_thread'})
      
          #启动线程
          t1.start()
          #启动另一个线程
          t2.start()
      
          #获取线程名
          print(t1.getName())
          print(t2.getName())
      
    • 继承式调用
      import threading
      import time
      
      class MyThread(threading.Thread):
          def __init__(self, num):
              threading.Thread.__init__(self)
              self.num = num
      
          #定义每个线程要运行的函数
          def run(self):
              print("running on number:%s" % self.num)
              time.sleep(3)
      
      if __name__ == '__main__':
      
          t1 = MyThread(1)
          t2 = MyThread(2)
          t1.start()
          t2.start()
      

       

  • IO密集型任务和CPU密集型任务
    • IO密集型任务:任务在执行过程中会有大量的IO阻塞,导致cpu空闲而对内存、磁盘的读写频繁
    • CPU密集型任务:任务执行过程中主要以占用cpu做计算为主,而读写空闲
    • python的多线程在IO密集型任务场景下使用可以缩短时间,提高效率,而在CPU密集型任务场景下却会降低效率并且增加执行的时间

       

  • 为什么多线程提升不了CPU密集型任务的效率?
    • 这是由于python解释器(Cpython)有一把GIL锁,它限制了多线程只能使用一个cpu计算,多余的cpu无法被使用

 

  • join()
    • 在子线程完成运行之前,这个子线程的父线程将一直被阻塞
posted @ 2018-08-28 16:40  运维00001  阅读(136)  评论(0编辑  收藏  举报