用户程序锁之递归锁、信号量

递归锁:

'''
递归锁:
需求:有多道门,同时只允许一个线程进门
如果用之前的锁,进来的时候进来了,出去的时候找不到对应的锁
 下面的程序中,锁的形象表示: { run3 { run1 } { run2 } }
 说明:这里有三把锁,如果用的是普通锁,进到run1里面就出不来了。因为找不到哪一把钥匙
 所以这里要用递归锁。原理是把钥匙存成字典,每次要开门就挨把挨把的试
'''
import threading
import time
def run1():
    print("run1----")
    lock.acquire()
    global num
    num += 1
    lock.release()
    return num
def run2():
    print("====run2")
    lock.acquire()
    global num2
    num2 += 1
    lock.release()
    return num2
def run3():
    lock.acquire()
    res = run1()
    print("---------run3")
    res2 = run2()
    lock.release()
    print(res, res2)

if __name__ == '__main__':
    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)

信号量

'''
信号量:Semaphore
锁同时只允许一个线程更改数据
而Semaphore是同时允许一定数量的线程更改数据
信号量与锁的区别是信号量同时有多把锁
5个线程每完成一个就放进去一个
'''
import threading
import time

def run(n):
    semaphore.acquire()
    time.sleep(2)
    print("run the thread:{0}".format(n))
    semaphore.release()


if __name__ == '__main__':
    semaphore = threading.BoundedSemaphore(5)  #最多允许5个线程同时运行
    for i in range(20):
        t = threading.Thread(target=run, args=(i,))
        t.start()
    while threading.active_count() != 1:
        pass
    else:
        print("all threads done")

 

posted on 2018-09-19 11:53 要一直走下去 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/staff/p/9673802.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值