歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python 多線程兩種實現方式

Python 多線程兩種實現方式

日期:2017/3/1 9:43:23   编辑:Linux編程

目前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. for i in xrange(10):
  19. thpool.append(myThread(i,2))
  20. for th in thpool:
  21. th.start()
  22. for th in thpool:
  23. th.join()
  24. print 'all Done at:', now()
  25. if __name__ == '__main__':
  26. main()

執行結果:

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved