python實現(xiàn)多線程的兩種方式
目前python 提供了幾種多線程實現(xiàn)方式 thread,threading,multithreading ,其中thread模塊比較底層,而threading模塊是對thread做了一些包裝,可以更加方便的被使用。
2.7版本之前python對線程的支持還不夠完善,不能利用多核CPU,但是2.7版本的python中已經(jīng)考慮改進這點,出現(xiàn)了multithreading 模塊。threading模塊里面主要是對一些線程的操作對象化,創(chuàng)建Thread的class。一般來說,使用線程有兩種模式:
A 創(chuàng)建線程要執(zhí)行的函數(shù),把這個函數(shù)傳遞進Thread對象里,讓它來執(zhí)行;
B 繼承Thread類,創(chuàng)建一個新的class,將要執(zhí)行的代碼 寫到run函數(shù)里面。
本文介紹兩種實現(xiàn)方法。
第一種 創(chuàng)建函數(shù)并且傳入Thread 對象中
t.py 腳本內(nèi)容
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 腳本內(nèi)容:
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()
以上就是本文的全部內(nèi)容嗎,希望對大家學(xué)習(xí)python程序設(shè)計有所幫助。
相關(guān)文章
python讀取.mat文件的數(shù)據(jù)及實例代碼
這篇文章主要介紹了python讀取.mat文件的數(shù)據(jù)的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-07-07
Django Haystack 全文檢索與關(guān)鍵詞高亮的實現(xiàn)
這篇文章主要介紹了Django Haystack 全文檢索與關(guān)鍵詞高亮的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
flask的orm框架SQLAlchemy查詢實現(xiàn)解析
這篇文章主要介紹了flask的orm框架SQLAlchemy查詢實現(xiàn)解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12
python?matplotlib畫圖時坐標軸重疊顯示不全和圖片保存時不完整的問題解決
最近工作中遇到了matplotlib保存圖片坐標軸不完整的問題,所以這篇文章主要給大家介紹了關(guān)于python?matplotlib畫圖時坐標軸重疊顯示不全和圖片保存時不完整問題的解決方法,需要的朋友可以參考下2022-07-07

