threading.Lock() lock.acquire() lock.release()
import threading
withlock=0 nolock=0 count=10000 lock=threading.Lock()
def inwithlock(): global withlock for i in range(count): lock.acquire() withlock+=1 lock.release() def dewithlock(): global withlock for i in range(count): lock.acquire() withlock-=1 lock.release() def innolock(): global nolock for i in range(count): nolock+=1 def denolock(): global nolock for i in range(count): nolock-=1
t1=threading.Thread(target=inwithlock) t2=threading.Thread(target=dewithlock) t3=threading.Thread(target=innolock) t4=threading.Thread(target=denolock) t1.start() t2.start() t3.start() t4.start() t1.join() t2.join() t3.join() t4.join() print("%s" % withlock) print("%s" % nolock)
import threading
count = 0 lock = threading.Lock()
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")
1.2 死锁
Lock在下面的情形下会发生死锁
Lock.acquire()
Lock.acquire()
Lock.release()
Lock.release()
连续两次acquire请求,会导致死锁,因为第一次获得锁之后还没有释放,第二次再来申请,程序就阻塞在这里,导致第一次申请到的锁无法释放
1.3 可重入锁
RLock就不存在1.2中所提到的死锁
RLock.acquire()
RLock.acquire()
RLock.release()
RLock.release()
但是要保证,有多少次acquire就有多少次release