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

首頁 > 編程 > Python > 正文

Python線程的兩種編程方式

2019-11-25 17:44:43
字體:
來源:轉載
供稿:網友

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

復制代碼 代碼如下:

###        thread_example.py  
import time 
import thread 
def timer(no,interval):  #自己寫的線程函數  
        while True:  
                print 'Thread :(%d) Time:%s'%(no,time.ctime())  
                time.sleep(interval)  
def test(): #使用thread.start_new_thread()來產生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])函數原型,其中function參數是你將要調用的線程函數;args是講傳遞給你的線程函數的參數,他必須是個tuple類型;而kwargs是可選的參數。
線程的結束一般依靠線程函數的自然結束;也可以在線程函數中調用thread.exit(),他拋出SystemExit exception,達到退出線程的目的。
2、通過調用threading模塊繼承threading.Thread類來包裝一個線程對象。請看代碼:
復制代碼 代碼如下:

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 泗水县| 长寿区| 台中县| 新蔡县| 永昌县| 东莞市| 时尚| 广汉市| 陇川县| 玉屏| 博客| 宜宾市| 宜丰县| 寿光市| 鄢陵县| 荣成市| 武功县| 金门县| 永平县| 东海县| 亚东县| 曲阜市| 西畴县| 米林县| 新绛县| 五华县| 台湾省| 新竹县| 冕宁县| 仙桃市| 如东县| 津南区| 沾益县| 樟树市| 延长县| 石楼县| 含山县| 赤水市| 怀化市| 富顺县| 平利县|