python(RLock(递归锁))

# Author:Sooele
import threading, time


def run1():
    print("grab the first part data") #
    lock.acquire() #获得一把锁
    global num # 回去全局变量num
    num += 1 #+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() #运行run1
    print('--------between run1 and run2-----') #
    res2 = run2() #执行run2
    lock.release() #释放
    print(res, res2)


if __name__ == '__main__':

    num, num2 = 0, 0    #生成2个变量0 1
    lock = threading.RLock()   #
    for i in range(10):    #循环 算上主线程11个线程
        t = threading.Thread(target=run3) #每个线程都启动run3
        t.start()

while threading.active_count() != 1:  #不等于1
    print(threading.active_count()) #判断当前线程
else:
    print('----all threads done---')  #如果等于1
    print(num, num2) #输出

发表评论