解析Python多線程編程兩種表現(xiàn)方式
本文介紹的是解析Python多線程編程兩種表現(xiàn)方式。Python中如果要使用線程的話,python的lib中提供了兩種方式。一種是函數(shù)式,一種是用類來包裝的線程對象。(例子已經(jīng)稍加修改)
1、調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新的線程,請看代碼:
Python語言 : 臨時自用代碼
- import time
- import thread
- import sys
- TIMEOUT = 20
- def myThread(no, interval):
- timeTotal = 0
- while True:
- if timeTotal < TIMEOUT:
- print "Thread(%d): timeTotal(%d)\n"%(no, timeTotal)
- timeTotal += interval
- else:
- print "Thread(%d) exits!\n"%no
- break
- def test():
- thread.start_new_thread(myThread, (1, 2))
- thread.start_new_thread(myThread, (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,達到退出線程的目的。
2、通過調(diào)用threading模塊繼承threading.Thread類來包裝一個線程對象。請看代碼
Python語言 : 臨時自用代碼
- import threading
- import time
- class MyThread(threading.Thread):
- def __init__(self, no, interval):
- threading.Thread.__init__(self)
- self.no = no
- self.interval = interval
- def run(self):
- while self.interval > 0:
- print "ThreadObject(%d) : total time(%d)\n"%(self.no, self.interval)
- time.sleep(1)
- self.interval -= 1
- def test():
- thread1 = MyThread(1, 10)
- thread2 = MyThread(2, 20)
- thread1.start()
- thread2.start()
- thread1.join()
- thread2.join()
- if __name__ == '__main__':
- test()
其實thread和threading的模塊中還包含了其他的很多關(guān)于多線程編程的東西,例如鎖、定時器、獲得激活線程列表等等,請大家仔細(xì)參考 python的文檔!
小結(jié):關(guān)于解析Python多線程編程兩種表現(xiàn)方式的內(nèi)容介紹完了,希望本文對你有所幫助。