1.
創建threading.Thread的子類來包裝一個線程對象
#encoding:utf8
import threading
import time
class timer(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):
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類的使用:
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模塊本身也提供了很多方法和其他的類,可以幫助我們更好的使用和管理線程。可以參看http://www.python.org/doc/2.5.2/lib/module-threading.html。
2.簡單的同步
#encoding:utf8
import threading
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 '\nThread(%s) locked,Number:%d'%(self.t_name,num)
if num >= 4:
mylock.release()
print '\nThread(%s) released,Number:%d'%(self.t_name,num)
break
num += 1
print '\nThread(%s) released,Number:%d'%(self.t_name,num)
mylock.release()
def test():
thread1 = myThread('A')
thread2 = myThread('B')
thread1.start()
thread2.start()
if __name__ == '__main__':
test()
Python的threading module是在建立在thread module基礎之上的一個module,在threading module中,暴露了許多thread module中的屬性。在thread module中,python提供了用戶級的線程同步工具“Lock”對象。而在threading module中,python又提供了Lock對象的變種: RLock對象。RLock對象內部維護著一個Lock對象,它是一種可重入的對象。對于Lock對象而言,如果一個線程連續兩次進行acquire操作,那么由于第一次acquire之后沒有release,第二次acquire將掛起線程。這會導致Lock對象永遠不會release,使得線程死鎖。RLock對象允許一個線程多次對其進行acquire操作,因為在其內部通過一個counter變量維護著線程acquire的次數。而且每一次的acquire操作必須有一個release操作與之對應,在所有的release操作完成之后,別的線程才能申請該RLock對象。修改共享數據的代碼成為“臨界區”。必須將所有“臨界區”都封閉在同一個鎖對象的acquire和release之間。