Python多線程學習

  Python多線程學習(線程使用) 
一.創建線程 
1.通過thread模塊中的start_new_thread(func,args)創建線程:
在Eclipse+pydev中敲出以下代碼:

Python代碼  收藏代碼

  1. # -*- coding: utf-8 -*-   

  2. import thread    

  3. def run_thread(n):    

  4.         for i in range(n):    

  5.             print i    

  6.     

  7. thread.start_new_thread(run_thread,(4,)) #參數一定是元組,兩個參數可以寫成(a,b)  

 

運行報錯如下:

 

Python代碼  收藏代碼

  1. Unhandled exception in thread started by   

  2. sys.excepthook is missing  

  3. lost sys.stderr  

 

網上查出原因是不建議使用thread,然後我在pythonGUI中做了測試,測試結果如下,顯然python是支持thread創建多線程的,在pydev中出錯原因暫時不明。

 

Python代碼  收藏代碼

  1. >>> import thread  

  2. >>> def run(n):  

  3.     for i in range(n):  

  4.         print i  

  5.   

  6. >>> thread.start_new_thread(run,(4,))  

  7. 98520  

  8.   

  9.   

  10. 1  

  11. >>>   

  12. 2  

  13. 3  

 

2.通過繼承threading.Thread創建線程,以下示例創建了兩個線程

Python代碼  收藏代碼

  1. # -*- coding: utf-8 -*-   

  2. ''''' 

  3. Created on 2012-8-8 

  4.  

  5. @author: jeromewei 

  6.  '''     

  7. from threading import Thread  

  8. import time  

  9. class race(Thread):  

  10.     def __init__(self,threadname,interval):  

  11.         Thread.__init__(self,name=threadname)  

  12.         self.interval = interval  

  13.         self.isrunning = True  

  14.           

  15.       

  16.     def run(self):       #重寫threading.Thread中的run()  

  17.         while self.isrunning:  

  18.             print 'thread %s is running,time:%s\n' %(self.getName(),time.ctime()) #獲得線程的名稱和當前時間  

  19.             time.sleep(self.interval)  

  20.     def stop(self):  

  21.         self.isrunning = False  

  22.   

  23. def test():  

  24.     thread1 = race('A',1)  

  25.     thread2 = race('B',2)  

  26.     thread1.start()  

  27.     thread2.start()  

  28.     time.sleep(5)  

  29.     thread1.stop()  

  30.     thread2.stop()  

  31.       

  32. if __name__ =='__main__':  

  33.     test()  

 

3. 在threading.Thread中指定目標函數作爲線程處理函數

Python代碼  收藏代碼

  1. # -*- coding: utf-8 -*-   

  2. from threading import Thread    

  3. def run_thread(n):    

  4.         for i in range(n):    

  5.             print i    

  6.     

  7. t1 = Thread(target=run_thread,args=(5,))#指定目標函數,傳入參數,這裏參數也是元組  

  8. t1.start()  #啓動線程  

 

二. threading.Thread中常用函數說明

 

       函數名 
                                              功能
run()如果採用方法2創建線程就需要重寫該方法
getName()獲得線程的名稱(方法2中有示例)
setName()設置線程的名稱
start()啓動線程
join(timeout) 
在join()位置等待另一線程結束後再繼續運行join()後的操作,timeout是可選項,表示最大等待時間
setDaemon(bool)
True:當父線程結束時,子線程立即結束;False:父線程等待子線程結束後才結束。默認爲False
isDaemon()判斷子線程是否和父線程一起結束,即setDaemon()設置的值
isAlive() 
判斷線程是否在運行

 

以上方法中,我將對join()和setDaemon(bool)作着重介紹,示例如下:


(1)join方法:

Java代碼  收藏代碼

  1. # -*- coding: utf-8 -*-   

  2. import threading    

  3. import time     #導入time模塊    

  4. class Mythread(threading.Thread):    

  5.     def __init__(self,threadname):    

  6.         threading.Thread.__init__(self,name = threadname)    

  7.     def run(self):    

  8.         time.sleep(2)   

  9.         for i in range(5):  

  10.             print '%s is running····'%self.getName()    

  11.      

  12. t2 = Mythread('B')    

  13. t2.start()  

  14. #t2.join()       

  15. for i in range(5):  

  16.     print 'the program is running···'  

 

這時的程序流程是:主線程先運行完,然後等待B線程運行,所以輸出結果爲:

 

Python代碼  收藏代碼

  1. the program is running···  

  2. the program is running···  

  3. the program is running···  

  4. is running····  

  5. is running····  

  6. is running····  

 

如果啓用t2.join() ,這時程序的運行流程是:當主線程運行到 t2.join() 時,它將等待 t2 運行完,然後再繼續運行t2.join() 後的操作,呵呵,你懂了嗎,所以輸出結果爲:

 

Python代碼  收藏代碼

  1. is running····  

  2. is running····  

  3. is running····  

  4. the program is running···  

  5. the program is running···  

  6. the program is running···  

 

(2)setDaemon方法:

Python代碼  收藏代碼

  1. # -*- coding: utf-8 -*-   

  2. import threading  

  3. import time   

  4. class myThread(threading.Thread):  

  5.     def __init__(self, threadname):  

  6.         threading.Thread.__init__(self, name=threadname)  

  7.           

  8.     def run(self):  

  9.         time.sleep(5)  

  10.         print '%s is running·······done'%self.getName()  

  11.       

  12. t=myThread('son thread')  

  13. #t.setDaemon(True)  

  14. t.start()  

  15. if t.isDaemon():  

  16.     print "the father thread and the son thread are done"  

  17. else:  

  18.     print "the father thread is waiting the son thread····"  

 

這段代碼的運行流程是:主線程打印完最後一句話後,等待son thread  運行完,然後程序才結束,所以輸出結果爲:

 

Python代碼  收藏代碼

  1. the father thread is waitting the son thread····  

  2. son thread is running·······done  

 

如果啓用t.setDaemon(True) ,這段代碼的運行流程是:當主線程打印完最後一句話後,不管 son thread 是否運行完,程序立即結束,所以輸出結果爲:

 

Python代碼  收藏代碼

  1. the father thread and the son thread are done  

 

三. 小結 
介紹到這裏,python多線程使用級別的知識點已全部介紹完了,下面我會分析一下python多線程的同步問題。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章