云萌主云应用官方论坛

标题: python多线程有几种实现方法 [打印本页]

作者: 骑单车的小女孩    时间: 2016-12-30 00:40
标题: python多线程有几种实现方法
python多线程有几种实现方法,都是什么?
        目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。2.7版本之前python对线程的支 持还不够完善,不能利用多核CPU,但是2.7版本的python中已经考虑改进这点,出现了multithreading  模块。threading模块里面主要是对一些线程的操作对象化,创建Thread的class。
        一般来说,使用线程有两种模式:
        A 创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;
        B 继承Thread类,创建一个新的class,将要执行的代码 写到run函数里面。

第一种 创建函数并且传入Thread 对象中
  1. import threading,time  
  2.     from time import sleep, ctime  
  3.     def now() :  
  4.         return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )  
  5.       
  6.     def test(nloop, nsec):  
  7.         print 'start loop', nloop, 'at:', now()  
  8.         sleep(nsec)  
  9.         print 'loop', nloop, 'done at:', now()  
  10.       
  11.     def main():  
  12.         print 'starting at:',now()  
  13.         threadpool=[]  
  14.       
  15.         for i in xrange(10):  
  16.             th = threading.Thread(target= test,args= (i,2))  
  17.             threadpool.append(th)  
  18.       
  19.         for th in threadpool:  
  20.             th.start()  
  21.       
  22.         for th in threadpool :  
  23.             threading.Thread.join( th )  
  24.       
  25.         print 'all Done at:', now()  
  26.       
  27.     if __name__ == '__main__':  
  28.             main()  
复制代码
第二种是创建一个新的class,将要执行的代码 写到run函数里面。
  1. import threading ,time  
  2.     from time import sleep, ctime  
  3.     def now() :  
  4.         return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )  
  5.       
  6.     class myThread (threading.Thread) :  
  7.           """docstring for myThread"""  
  8.           def __init__(self, nloop, nsec) :  
  9.               super(myThread, self).__init__()  
  10.               self.nloop = nloop  
  11.               self.nsec = nsec  
  12.       
  13.           def run(self):  
  14.               print 'start loop', self.nloop, 'at:', ctime()  
  15.               sleep(self.nsec)  
  16.               print 'loop', self.nloop, 'done at:', ctime()  
  17.     def main():  
  18.          thpool=[]  
  19.          print 'starting at:',now()  
  20.          
  21.          for i in xrange(10):  
  22.              thpool.append(myThread(i,2))  
  23.                
  24.          for th in thpool:  
  25.              th.start()  
  26.          
  27.          for th in thpool:  
  28.              th.join()  
  29.          
  30.          print 'all Done at:', now()  
  31.       
  32.     if __name__ == '__main__':  
  33.             main()  
复制代码

来源:http://www.open-open.com/code/view/1434096618379






欢迎光临 云萌主云应用官方论坛 (https://www.yunmengzhu.com/) Powered by Discuz! X3.4