Python線程編程的兩種方式

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

一、調用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(timer,(1,1))  #使用thread.start_new_thread()來產生2個新的線程
        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,達到退出線程的目的。函數

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

### threading_example.py
import threading
import time
class timer(threading.Thread):             #個人timer類繼承自threading.Thread類
        def __init__(self,no,interval): 
                threading.Thread.__init__(self)      #在我重寫__init__方法的時候要記得調用基類的__init__方法
                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的文檔!對象

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=107470blog

相關文章
相關標籤/搜索