国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python線程的兩種編程方式

2020-02-23 00:43:18
字體:
供稿:網(wǎng)友

Python中如果要使用線程的話,python的lib中提供了兩種方式。一種是函數(shù)式,一種是用類來包裝的線程對象。舉兩個簡單的例子希望起到拋磚引玉的作用,關(guān)于多線程編程的其他知識例如互斥、信號量、臨界區(qū)等請參考python的文檔及相關(guān)資料。
1、調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新的線程,請看代碼:
代碼如下:
###        thread_example.py  
import time 
import thread 
def timer(no,interval):  #自己寫的線程函數(shù)  
        while True:  
                print 'Thread :(%d) Time:%s'%(no,time.ctime())  
                time.sleep(interval)  
def test(): #使用thread.start_new_thread()來產(chǎn)生2個新的線程  
        thread.start_new_thread(timer,(1,1))    
        thread.start_new_thread(timer,(2,3))  
if __name__=='__main__':  
        test() 

這個是thread.start_new_thread(function,args[,kwargs])函數(shù)原型,其中function參數(shù)是你將要調(diào)用的線程函數(shù);args是講傳遞給你的線程函數(shù)的參數(shù),他必須是個tuple類型;而kwargs是可選的參數(shù)。
線程的結(jié)束一般依靠線程函數(shù)的自然結(jié)束;也可以在線程函數(shù)中調(diào)用thread.exit(),他拋出SystemExit exception,達(dá)到退出線程的目的。
2、通過調(diào)用threading模塊繼承threading.Thread類來包裝一個線程對象。請看代碼:
代碼如下:
import threading 
import time 
class timer(threading.Thread):     #我的timer類繼承自threading.Thread類  
    def __init__(self,no,interval):   
        #在我重寫__init__方法的時候要記得調(diào)用基類的__init__方法  
        threading.Thread.__init__(self)       
        self.no=no  
        self.interval=interval  
          
    def run(self):  #重寫run()方法,把自己的線程函數(shù)的代碼放到這里  
        while True:  
            print 'Thread Object (%d), Time:%s'%(self.no,time.ctime())  
            time.sleep(self.interval)  

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 榆树市| 凤城市| 雅安市| 枝江市| 玉环县| 且末县| 宁晋县| 东兴市| 湘潭县| 山阳县| 临潭县| 辽宁省| 甘南县| 嵊州市| 固阳县| 溆浦县| 临武县| 化州市| 盘锦市| 冕宁县| 屏南县| 抚宁县| 丽江市| 瑞昌市| 潼南县| 镇安县| 深水埗区| 尼木县| 青铜峡市| 平顶山市| 工布江达县| 酉阳| 钟祥市| 和林格尔县| 泰和县| 论坛| 宜丰县| 瓮安县| 海门市| 眉山市| 略阳县|