Python多線程學習資料
2020-02-23 04:50:03
供稿:網友
一、Python中的線程使用:
Python中使用線程有兩種方式:函數或者用類來包裝線程對象。
1、 函數式:調用thread模塊中的start_new_thread()函數來產生新線程。如下例:
代碼如下:
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()
上面的例子定義了一個線程函數timer,它打印出10條時間記錄后退出,每次打印的間隔由interval參數決定。thread.start_new_thread(function, args[, kwargs])的第一個參數是線程函數(本例中的timer方法),第二個參數是傳遞給線程函數的參數,它必須是tuple類型,kwargs是可選參數。
線程的結束可以等待線程自然結束,也可以在線程函數中調用thread.exit()或thread.exit_thread()方法。
2、 創建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()
就我個人而言,比較喜歡第二種方式,即創建自己的線程類,必要時重寫threading.Thread類的方法,線程的控制可以由自己定制。
threading.Thread類的使用:
1,在自己的線程類的__init__里調用threading.Thread.__init__(self, name = threadname)
Threadname為線程的名字
2, run(),通常需要重寫,編寫代碼實現做需要的功能。
3,getName(),獲得線程對象名稱
4,setName(),設置線程對象名稱
5,start(),啟動線程
6,jion([timeout]),等待另一線程結束后再運行。
7,setDaemon(bool),設置子線程是否隨主線程一起結束,必須在start()之前調用。默認為False。
8,isDaemon(),判斷線程是否隨主線程一起結束。
9,isAlive(),檢查線程是否在運行中。
此外threading模塊本身也提供了很多方法和其他的類,可以幫助我們更好的使用和管理線程??梢詤⒖磆ttp://www.python.org/doc/2.5.2/lib/module-threading.html。