Python多線程學(xué)習(xí)資料
2020-02-23 04:50:03
供稿:網(wǎng)友
一、Python中的線程使用:
Python中使用線程有兩種方式:函數(shù)或者用類來包裝線程對象。
1、 函數(shù)式:調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新線程。如下例:
代碼如下:
import time
import thread
def timer(no, interval):
cnt = 0
while cnt<10:
print 'Thread:(%d) Time:%s/n'%(no, time.ctime())
time.sleep(interval)
cnt+=1
thread.exit_thread()
def test(): #Use thread.start_new_thread() to create 2 new threads
thread.start_new_thread(timer, (1,1))
thread.start_new_thread(timer, (2,2))
if __name__=='__main__':
test()
上面的例子定義了一個線程函數(shù)timer,它打印出10條時間記錄后退出,每次打印的間隔由interval參數(shù)決定。thread.start_new_thread(function, args[, kwargs])的第一個參數(shù)是線程函數(shù)(本例中的timer方法),第二個參數(shù)是傳遞給線程函數(shù)的參數(shù),它必須是tuple類型,kwargs是可選參數(shù)。
線程的結(jié)束可以等待線程自然結(jié)束,也可以在線程函數(shù)中調(diào)用thread.exit()或thread.exit_thread()方法。
2、 創(chuàng)建threading.Thread的子類來包裝一個線程對象,如下例:
代碼如下:
import threading
import time
class timer(threading.Thread): #The timer class is derived from the class threading.Thread
def __init__(self, num, interval):
threading.Thread.__init__(self)
self.thread_num = num
self.interval = interval
self.thread_stop = False
def run(self): #Overwrite run() method, put what you want the thread do here
while not self.thread_stop:
print 'Thread Object(%d), Time:%s/n' %(self.thread_num, time.ctime())
time.sleep(self.interval)
def stop(self):
self.thread_stop = True
def test():
thread1 = timer(1, 1)
thread2 = timer(2, 2)
thread1.start()
thread2.start()
time.sleep(10)
thread1.stop()
thread2.stop()
return
if __name__ == '__main__':
test()
就我個人而言,比較喜歡第二種方式,即創(chuàng)建自己的線程類,必要時重寫threading.Thread類的方法,線程的控制可以由自己定制。
threading.Thread類的使用:
1,在自己的線程類的__init__里調(diào)用threading.Thread.__init__(self, name = threadname)
Threadname為線程的名字
2, run(),通常需要重寫,編寫代碼實現(xiàn)做需要的功能。
3,getName(),獲得線程對象名稱
4,setName(),設(shè)置線程對象名稱
5,start(),啟動線程
6,jion([timeout]),等待另一線程結(jié)束后再運行。
7,setDaemon(bool),設(shè)置子線程是否隨主線程一起結(jié)束,必須在start()之前調(diào)用。默認為False。
8,isDaemon(),判斷線程是否隨主線程一起結(jié)束。
9,isAlive(),檢查線程是否在運行中。
此外threading模塊本身也提供了很多方法和其他的類,可以幫助我們更好的使用和管理線程。可以參看http://www.python.org/doc/2.5.2/lib/module-threading.html。