python 多线程 锁lock/rlock(并行编程 4)

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

global var

count = 0
lock = threading.Lock()

Define a function for the thread

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) )

Create and run threads as follows

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")

RLOCK和LOCK的区别

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

你可能感兴趣的:(python 多线程 锁lock/rlock(并行编程 4))