【Python】python 多執行緒兩種實現方式

楊奇龍發表於2014-06-08
目前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 物件
t.py 指令碼內容
  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. def test(nloop, nsec):
  6.     print 'start loop', nloop, 'at:', now()
  7.     sleep(nsec)
  8.     print 'loop', nloop, 'done at:', now()

  9. def main():
  10.     print 'starting at:',now()
  11.     threadpool=[]

  12.     for i in xrange(10):
  13.         th = threading.Thread(target= test,args= (i,2))
  14.         threadpool.append(th)

  15.     for th in threadpool:
  16.         th.start()

  17.     for th in threadpool :
  18.         threading.Thread.join( th )

  19.     print 'all Done at:', now()

  20. if __name__ == '__main__':
  21.         main()
執行結果:


thclass.py 指令碼內容:
  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. class myThread (threading.Thread) :
  6.       """docstring for myThread"""
  7.       def __init__(self, nloop, nsec) :
  8.           super(myThread, self).__init__()
  9.           self.nloop = nloop
  10.           self.nsec = nsec

  11.       def run(self):
  12.           print 'start loop', self.nloop, 'at:', ctime()
  13.           sleep(self.nsec)
  14.           print 'loop', self.nloop, 'done at:', ctime()
  15. def main():
  16.      thpool=[]
  17.      print 'starting at:',now()
  18.     
  19.      for i in xrange(10):
  20.          thpool.append(myThread(i,2))
  21.          
  22.      for th in thpool:
  23.          th.start()
  24.    
  25.      for th in thpool:
  26.          th.join()
  27.     
  28.      print 'all Done at:', now()

  29. if __name__ == '__main__':
  30.         main()
執行結果:

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22664653/viewspace-1178285/,如需轉載,請註明出處,否則將追究法律責任。

相關文章