Python 中的Lock與RLock
如果多個執行緒共同對某個資料修改,則可能出現不可預料的結果,為了保證資料的正確性,需要對多個執行緒進行同步,使用 Thread 物件的 Lock 和 Rlock 可以實現簡單的執行緒同步,這兩個物件都有 acquire 方法和 release 方法,分別用來獲取和釋放鎖 啟動3個執行緒對count進行操作
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才能真正釋放所佔用的瑣