這篇文章主要介紹了Python實現多線程的兩種方式,結合實例形式分析了通過自定義函數傳遞Thread對象以及繼承Thread類兩種多線程實現方式相關操作技巧,需要的朋友可以參考下
本文實例講述了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 對象中
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()
執行結果:
第二種 創建繼承自Thread的類
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學習扣qun:774711191 ,看看前輩們是如何學習的!從基礎的python腳本到web開發、爬蟲、django、數據挖掘等【PDF,實戰源碼】,零基礎到項目實戰的資料都有整理。送給每一位python的小夥伴!每天都有大牛定時講解Python技術,分享一些學習的方法和需要注意的小細節,點擊加入我們的 python學習者聚集地