线程锁,递归锁_第1张图片

##线程锁应用

import time,threading
python中自己加锁了所以用不着!
def run(n):
    lock.acquire() #获取一把锁
    global  num
    num+=1
    lock.release() #释放锁

lock=threading.Lock()
num=0
loot=[] #创建一个空列表(存线程实例)
for i in range (50):
    t=threading.Thread(target=run,args=("t-%s"%i,))
    t.start()
    loot.append(t) #为了不阻塞后面的线程启动,不在这里join,先放到一个列表里

for t in loot:#循环线程实例列表,等待所有线程执行完毕
    t.join() #等待一个线程全部执行完再执行其他线程(把并程改成了串行)
print("-----ddddd-----",threading.current_thread(),threading.active_count())#看是否是主线程,活跃的线程数量
print("num:",num)

##递归锁的意思是相当于已过字典。。。每开一道门就存门对应的钥匙数据,退出时去字典找对应的门用的钥匙

def run1():
    print("grab the first part data")
    lock.acquire()
    global num
    num+=1
    lock.release()
    return num

def run2():
    print("grab the second part data")
    lock.acquire()
    global  num2
    num2+=1
    lock.release()
    return num2

def run3():
    lock.acquire()
    res=run1()
    print("----between run1 and run2-----")
    res2=run2()
    lock.release()
    print(res,res2)

num,num2=0,0
lock=threading.RLock() ##递归锁创建
for i in range(10):
    t=threading.Thread(target=run3)
    t.start()

while threading.active_count()!=1:
    print(threading.active_count())
else:
    print("------all threads done------")
    print(num,num2)