python多線程學習:
python中的線程使用的兩種方式:函數或者用類來包裝線程對象。
1、函數式:調用thread模塊中start_new_thread()函數來產生新線程。
#!/usr/bin/env python #coding:utf-8 ''' 會出現一下的錯誤,在pydev中就會出現這樣的錯誤,原因不明。一般不建議使用 thread這個模塊。 Unhandled exception in thread started by sys.excepthook is missing lost sys.stderr Unhandled exception in thread started by sys.excepthook is missing lost sys.stderr ''' import thread import time 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(): thread.start_new_thread(timer,(1,1)) thread.start_new_thread(timer, (2,2)) if __name__=='__main__': test()
2、創建threading.Thread 的子類來包裝一個線程對象。
#!/usr/bin/env python #coding:utf-8 from threading import Thread import time from _ast import Num class timer(Thread): def __init__(self,num,interval): Thread.__init__(self) self.thread_num = num self.interval = interval self.thread_stop = False def run(self): 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(): t1 = timer(1,1) t2 = timer(2,2) t1.start() t2.start() time.sleep(10) t1.stop() t2.stop() return if __name__=='__main__': test()
threading.Thread類的使用:
1、在自己的線程類的__inin__()裏調用threading.Thread.__init__(self,name=threadname)
2、run(),通常需要重寫,編寫代碼實現所需要的功能。
3、getName(),獲得線程對象名稱
4、setName(),設置線程對象名稱
5、start(),啓動線程
6、jion(),等待另一線程的結束後再運行
7、setDaemon(),設置子線程是否隨主線程一起結束,必須在start()之前調用。默認爲False。
8、isDaemon(),判斷線程是否隨主線程一起結束。
9、isAlive(),檢查線程是否在運行中。
線程同步:數據共享。當多個線程都要去修改某一個共享數據的時候,我們需要對數據訪問進行同步。
1、簡單同步
最簡單的同步機制就是‘鎖’。鎖對象由threading.RLock類創建。線程可以使用鎖的acquire()方法獲得鎖,這樣鎖
就進入了“locked”狀態。每次只有一個線程可以獲得鎖。這個線程使用完資源以後調用鎖的release()方法來釋放鎖,使鎖
進入“unlocked”狀態。
python中的thread模塊和Lock對象是python提供的低級線程控制工具,比較簡單。
#!/usr/bin/env python #coding:utf-8 import threading import time mylock = threading.RLock() num = 0 class myThread(threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.t_name = name def run(self): global num while True: mylock.acquire()#得到鎖 print 'Thread(%s) locked, Number: %d'%(self.t_name, num) if num >=5: mylock.release() print 'Thread %s release! num =%d'%(self.t_name,num) break num+=1 print 'Thread %s released! num = %d'%(self.t_name,num) mylock.release() def test(): t1 = myThread('A') t2 = myThread('B') t1.start() t2.start() if __name__== '__main__': test()
2、條件同步
使用wait()和set()fangfa 進行加鎖和釋放鎖。
還可以使用隊列。Python中的Queue對象也提供了對線程同步的支持。使用Queue對象可以實現多個生產者和多個消費者形成的FIFO的隊列。