import threading
count = 0
def print_time(threadName):
global count
c = 0
while(c<100):
c+=1
count +=1
print("{0}:set count to {1}".format(threadName,count))
try:
threading.Thread( target=print_time, args=("Thread-1", ) ).start()
threading.Thread( target=print_time, args=("Thread-2", ) ).start()
threading.Thread( target=print_time, args=("Thread-3", ) ).start()
except Exception as e:
print("Error: unable to start thread")
結果“ 每個thread對count進行改動期間while(c<100),有其它的thread插入進來改動count

通過threading.Lock() 實現,通過Lock的acquire()和release()函數來控制加鎖和解鎖,使用簡單得方法 with實現
import threading
lock = threading.Lock()
count = 0
def print_time(threadName):
global count
c = 0
with lock:
while(c<100):
c+=1
count +=1
print("{0}:set count to {1}".format(threadName,count))
try:
threading.Thread( target=print_time, args=("Thread-1", ) ).start()
threading.Thread( target=print_time, args=("Thread-2", ) ).start()
threading.Thread( target=print_time, args=("Thread-3", ) ).start()
except Exception as e:
print("Error: unable to start thread")
結果

通過threading.Rlock() 實現
import threading
rlock = threading.RLock()
count = 0
def print_time(threadName):
global count
c = 0
with rlock:
while(c<100):
c+=1
count +=1
print("{0}:set count to {1}".format(threadName,count))
try:
threading.Thread( target=print_time, args=("Thread-1", ) ).start()
threading.Thread( target=print_time, args=("Thread-2", ) ).start()
threading.Thread( target=print_time, args=("Thread-3", ) ).start()
except Exception as e:
print("Error: unable to start thread")
j結果

Lock和Rlock的區別
import threading lock = threading.Lock() #Lock對象 lock.acquire() lock.acquire() #產生了死瑣。 lock.release() lock.release()
import threading lock = threading.RLock() #Lock對象 lock.acquire() lock.acquire() 程序不會堵塞 lock.release() lock.release()
| Locks | RLocks |
|---|---|
| A Lock object can not be acquired again by any thread unless it is released by the thread which which is accessing the shared resource. 一個lock被釋放前不能被其他線程獲得acquire |
An RLock object can be acquired numerous times by any thread. 一個Rlock可以被其他任意線程獲得 |
| A Lock object can be released by any thread. 一個lock可以被其他線程釋放 |
An RLock object can only be released by the thread which acquired it. Rlock只能被獲得他的線程釋放 |
| A Lock object can be owned by one lock被一個線程占有 |
An RLock object can be owned by many threads Rlock可以被其他線程獲得 |
| Execution of a Lock object is faster. lock的運行速度快 |
Execution of an RLock object is slower than a Lock object 運行速度比lock慢 |
這兩種瑣的主要區別是:RLock允許在同一線程中被多次acquire。而Lock卻不允許這種情況。注意:如果使用RLock,那么acquire和release必須成對出現,即調用了n次acquire,必須調用n次的release才能真正釋放所占用的瑣
