1.
創(chuàng)建threading.Thread的子類來包裝一個(gè)線程對(duì)象
#encoding:utf8
import threading
import time
class timer(threading.Thread):
def __init__(self,num,interval):
threading.Thread.__init__(self)
#設(shè)置產(chǎn)生線程的個(gè)數(shù)
self.thread_num = num
#產(chǎn)生線程的相隔時(shí)間
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__里調(diào)用threading.Thread.__init__(self, name = threadname)
Threadname為線程的名字
2). run(),通常需要重寫,編寫代碼實(shí)現(xiàn)做需要的功能。
3).getName(),獲得線程對(duì)象名稱
4).setName(),設(shè)置線程對(duì)象名稱
5).start(),啟動(dòng)線程
6).jion([timeout]),等待另一線程結(jié)束后再運(yùn)行。
7).setDaemon(bool),設(shè)置子線程是否隨主線程一起結(jié)束,必須在start()之前調(diào)用。默認(rèn)為False。
8).isDaemon(),判斷線程是否隨主線程一起結(jié)束。
9).isAlive(),檢查線程是否在運(yùn)行中。
此外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基礎(chǔ)之上的一個(gè)module,在threading module中,暴露了許多thread module中的屬性。在thread module中,python提供了用戶級(jí)的線程同步工具“Lock”對(duì)象。而在threading module中,python又提供了Lock對(duì)象的變種: RLock對(duì)象。RLock對(duì)象內(nèi)部維護(hù)著一個(gè)Lock對(duì)象,它是一種可重入的對(duì)象。對(duì)于Lock對(duì)象而言,如果一個(gè)線程連續(xù)兩次進(jìn)行acquire操作,那么由于第一次acquire之后沒有release,第二次acquire將掛起線程。這會(huì)導(dǎo)致Lock對(duì)象永遠(yuǎn)不會(huì)release,使得線程死鎖。RLock對(duì)象允許一個(gè)線程多次對(duì)其進(jìn)行acquire操作,因?yàn)樵谄鋬?nèi)部通過一個(gè)counter變量維護(hù)著線程acquire的次數(shù)。而且每一次的acquire操作必須有一個(gè)release操作與之對(duì)應(yīng),在所有的release操作完成之后,別的線程才能申請(qǐng)?jiān)?/span>RLock對(duì)象。修改共享數(shù)據(jù)的代碼成為“臨界區(qū)”。必須將所有“臨界區(qū)”都封閉在同一個(gè)鎖對(duì)象的acquire和release之間。