Python線程編程的兩種方式

Python中如果要使用線程的話,python的lib中提供了兩種方式。一種是函數式,一種是用類來包裝的線程對象。舉兩個簡單的例子希望起到拋磚引玉的作用,關於多線程編程的其他知識例如互斥、信號量、臨界區等請參考python的文檔及相關資料。

1、調用thread模塊中的start_new_thread()函數來產生新的線程,請看代碼:

python 代碼
  1. ###        thread_example.py   
  2. import time  
  3. import thread  
  4. def timer(no,interval):  #自己寫的線程函數   
  5.         while True:   
  6.                 print 'Thread :(%d) Time:%s'%(no,time.ctime())   
  7.                 time.sleep(interval)   
  8. def test(): #使用thread.start_new_thread()來產生2個新的線程   
  9.         thread.start_new_thread(timer,(1,1))     
  10.         thread.start_new_thread(timer,(2,3))   
  11. if __name__=='__main__':   
  12.         test()  

 

這個是thread.start_new_thread(function,args[,kwargs])函數原型,其中function參數是你將要調用的線程函數;args是講傳遞給你的線程函數的參數,他必須是個tuple類型;而kwargs是可選的參數
線程的結束一般依靠線程函數的自然結束;也可以在線程函數中調用thread.exit(),他拋出SystemExit exception,達到退出線程的目的。

2、通過調用threading模塊繼承threading.Thread類來包裝一個線程對象。請看代碼:

python 代碼
  1. import threading  
  2. import time  
  3. class timer(threading.Thread):     #我的timer類繼承自threading.Thread類   
  4.     def __init__(self,no,interval):    
  5.         #在我重寫__init__方法的時候要記得調用基類的__init__方法   
  6.         threading.Thread.__init__(self)        
  7.         self.no=no   
  8.         self.interval=interval   
  9.            
  10.     def run(self):  #重寫run()方法,把自己的線程函數的代碼放到這裏   
  11.         while True:   
  12.             print 'Thread Object (%d), Time:%s'%(self.no,time.ctime())   
  13.             time.sleep(self.interval)   
  14.                
  15. def test():   
  16.     threadone=timer(1,1)    #產生2個線程對象   
  17.     threadtwo=timer(2,3)   
  18.     threadone.start()   #通過調用線程對象的.start()方法來激活線程   
  19.     threadtwo.start()   
  20.        
  21. if __name__=='__main__':   
  22.     test()  

其實thread和threading的模塊中還包含了其他的很多關於多線程編程的東西,例如鎖、定時器、獲得激活線程列表等等,請大家仔細參考python的文檔!

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