首頁  >  文章  >  後端開發  >  python實作多執行緒的方式

python實作多執行緒的方式

高洛峰
高洛峰原創
2017-03-02 16:13:221397瀏覽

目前python 提供了幾種多執行緒實作方式 thread,threading,multithreading ,其中thread模組比較底層,而threading模組是對thread做了一些包裝,可以更方便的使用。 

2.7版本之前python對執行緒的支援還不夠完善,不能利用多核心CPU,但是2.7版本的python中已經考慮改進這點,出現了multithreading  模組。 threading模組裡面主要是對一些執行緒的操作物件化,創建Thread的class。一般來說,使用執行緒有兩種模式:

A 建立執行緒要執行的函數,把這個函數傳遞進Thread物件裡,讓它執行;
B 繼承執行緒要執行的函數,把這個函數傳遞進Thread物件裡,讓它執行;
B 繼承執行緒要執行的函數,把這個函數傳遞進Thread物件裡,讓它來執行;
B 繼承Thread類,建立一個新的class,將要執行的程式碼寫到run函數裡面。



本文介紹兩種實作方法。 第一種建立函數並且傳入Thread 物件中t.py 腳本內容

##

import threading,time
from time import sleep, ctime
def now() :
  return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def test(nloop, nsec):
  print 'start loop', nloop, 'at:', now()
sleep(nsec)
  print 'loop', nloop, 'done at:', now()
def main():
  print 'starting at:',now()
  threadpool=[]
for i in xrange(10):
    th = threading.Thread(target= test,args= (i,2))
    threadpool.append(th)
for th in threadpool:
    th.start()
for th in threadpool :
    threading.Thread.join( th )
  print 'all Done at:', now()
if __name__ == '__main__':
    main()

 thclass.py 腳本內容:

#

import threading ,time
from time import sleep, ctime
def now() :
  return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
class myThread (threading.Thread) :
"""docstring for myThread"""
   def __init__(self, nloop, nsec) :
     super(myThread, self).__init__()
     self.nloop = nloop
     self.nsec = nsec
   def run(self):
     print 'start loop', self.nloop, 'at:', ctime()
sleep(self.nsec)
     print 'loop', self.nloop, 'done at:', ctime()
def main():
   thpool=[]
   print 'starting at:',now()
for i in xrange(10):
     thpool.append(myThread(i,2))
for th in thpool:
     th.start()
for th in thpool:
     th.join()
   print 'all Done at:', now()
if __name__ == '__main__':
    main()

以上就是本文的全部內容嗎,希望對大家學習python程式設計有幫助。


更多python實作多執行緒的方式相關文章請關注PHP中文網!


####
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn