欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python線程的兩種編程方式

 更新時(shí)間:2015年04月14日 10:44:36   投稿:junjie  
這篇文章主要介紹了Python線程的兩種編程方式,Python中如果要使用線程的話,一種是函數(shù)式,一種是用類(lèi)來(lái)包裝的線程對(duì)象,需要的朋友可以參考下

Python中如果要使用線程的話,python的lib中提供了兩種方式。一種是函數(shù)式,一種是用類(lèi)來(lái)包裝的線程對(duì)象。舉兩個(gè)簡(jiǎn)單的例子希望起到拋磚引玉的作用,關(guān)于多線程編程的其他知識(shí)例如互斥、信號(hào)量、臨界區(qū)等請(qǐng)參考python的文檔及相關(guān)資料。
1、調(diào)用thread模塊中的start_new_thread()函數(shù)來(lái)產(chǎn)生新的線程,請(qǐng)看代碼:

復(fù)制代碼 代碼如下:

###        thread_example.py  
import time 
import thread 
def timer(no,interval):  #自己寫(xiě)的線程函數(shù)  
        while True:  
                print 'Thread :(%d) Time:%s'%(no,time.ctime())  
                time.sleep(interval)  
def test(): #使用thread.start_new_thread()來(lái)產(chǎn)生2個(gè)新的線程  
        thread.start_new_thread(timer,(1,1))    
        thread.start_new_thread(timer,(2,3))  
if __name__=='__main__':  
        test() 

這個(gè)是thread.start_new_thread(function,args[,kwargs])函數(shù)原型,其中function參數(shù)是你將要調(diào)用的線程函數(shù);args是講傳遞給你的線程函數(shù)的參數(shù),他必須是個(gè)tuple類(lèi)型;而kwargs是可選的參數(shù)。
線程的結(jié)束一般依靠線程函數(shù)的自然結(jié)束;也可以在線程函數(shù)中調(diào)用thread.exit(),他拋出SystemExit exception,達(dá)到退出線程的目的。
2、通過(guò)調(diào)用threading模塊繼承threading.Thread類(lèi)來(lái)包裝一個(gè)線程對(duì)象。請(qǐng)看代碼:
復(fù)制代碼 代碼如下:

import threading 
import time 
class timer(threading.Thread):     #我的timer類(lèi)繼承自threading.Thread類(lèi)  
    def __init__(self,no,interval):   
        #在我重寫(xiě)__init__方法的時(shí)候要記得調(diào)用基類(lèi)的__init__方法  
        threading.Thread.__init__(self)       
        self.no=no  
        self.interval=interval  
          
    def run(self):  #重寫(xiě)run()方法,把自己的線程函數(shù)的代碼放到這里  
        while True:  
            print 'Thread Object (%d), Time:%s'%(self.no,time.ctime())  
            time.sleep(self.interval)  
              
def test():  
    threadone=timer(1,1)    #產(chǎn)生2個(gè)線程對(duì)象  
    threadtwo=timer(2,3)  
    threadone.start()   #通過(guò)調(diào)用線程對(duì)象的.start()方法來(lái)激活線程  
    threadtwo.start()  
      
if __name__=='__main__':  
    test()
 
其實(shí)thread和threading的模塊中還包含了其他的很多關(guān)于多線程編程的東西,例如鎖、定時(shí)器、獲得激活線程列表等等,請(qǐng)大家仔細(xì)參考python的文檔!

相關(guān)文章

最新評(píng)論