同步锁、递归锁

同步锁

线程申请到gillock才能被cpu执行

lock=threading.LOCK()

lock.acquire() 获取

lock.release() 释放

import threading,time
def sub():
    print(30)
    global num
    lock.acquire()
    num-=1
    print(999)
    time.sleep(1)
    lock.release()
    print(25,t)
num=100
l=[]
lock=threading.Lock()
for i in range(100):
    t=threading.Thread(target=sub)
    t.start()
    l.append(t)
for t in l:
    t.join()
print(num)
同步锁

递归锁

用来解决死锁

r_lock=threading.RLock()

r_lock.acquire()  计算器加1,只要内部计算器>0,其它线程无法获取

r_lock.release()  计算器减1

递归锁:内部维持多把锁

import threading,time
class Mythread(threading.Thread):
    def actionA(self):
        r_lock.acquire()
        print(self.name,'get A',time.ctime())
        time.sleep(1)
        r_lock.acquire()
        print(self.name,'get B',time.ctime())
        time.sleep(2)
        r_lock.release()
        r_lock.release()
    def actionB(self):
        r_lock.acquire()
        print(self.name, 'get B', time.ctime())
        time.sleep(1)
        r_lock.acquire()
        print(self.name, 'get A', time.ctime())
        time.sleep(2)
        r_lock.release()
        r_lock.release()
    def run(self):
        self.actionA()
        self.actionB()
l=[]
r_lock=threading.RLock()
for i in range(5):
    t=Mythread()
    t.start()
    l.append(t)
for t in l:
    print(4)
    t.join()
    print(3,t)
print('结束')
递归锁

转载于:https://www.cnblogs.com/jintian/p/11000923.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值