Lock()與RLock()鎖
資源總是有限的,程式執行如果對同一個物件進行操作,則有可能造成資源的爭用,甚至導致死鎖
也可能導致讀寫混亂
鎖提供如下方法:
1.Lock.acquire([blocking])
2.Lock.release()
3.threading.Lock() 載入執行緒的鎖物件,是一個基本的鎖物件,一次只能一個鎖定,其餘鎖請求,需等待鎖釋放後才能獲取
4.threading.RLock() 多重鎖,在同一執行緒中可用被多次acquire。如果使用RLock,那麼acquire和release必須成對出現,
呼叫了n次acquire鎖請求,則必須呼叫n次的release才能線上程中釋放鎖物件
例如:
無鎖:
#coding=utf8
import threading
import time
num = 0
def sum_num(i):
global num
time.sleep(1)
num +=i
print num
print '%s thread start!'%(time.ctime())
try:
for i in range(6):
t =threading.Thread(target=sum_num,args=(i,))
t.start()
except KeyboardInterrupt,e:
print "you stop the threading"
print '%s thread end!'%(time.ctime())
輸出:
Sun May 28 20:54:59 2017 thread start!
Sun May 28 20:54:59 2017 thread end!
01
3
710
15
1
2
3
4
5
6
結果顯示混亂
引入鎖:
#coding=utf8
import threading
import time
num = 0
def sum_num(i):
lock.acquire()
global num
time.sleep(1)
num +=i
print num
lock.release()
print '%s thread start!'%(time.ctime())
try:
lock=threading.Lock()
list = []
for i in range(6):
t =threading.Thread(target=sum_num,args=(i,))
list.append(t)
t.start()
for threadinglist in list:
threadinglist.join()
except KeyboardInterrupt,e:
print "you stop the threading"
print '%s thread end!'%(time.ctime())
結果:
Sun May 28 21:15:37 2017 thread start!
0
1
3
6
10
15
Sun May 28 21:15:43 2017 thread end!
其中:
lock=threading.Lock()載入鎖的方法也可以換成lock=threading.RLock()
如果將上面的sum_num修改為:
lock.acquire()
global num
lock.acquire()
time.sleep(1)
num +=i
lock.release()
print num
lock.release()
那麼:
lock=threading.Lock() 載入的鎖,則一直處於等待中,鎖等待
而lock=threading.RLock() 執行正常