• 线程锁,


    from threading import Thread,Lock

    noodle_lock = Lock()
    chazi_lock = Lock()
    def eat1(name):
    noodle_lock.acquire()
    print('%s拿到了面条'%name)
    chazi_lock.acquire()
    print('%s拿到了叉子'%name)
    print('%s吃面'%name)
    chazi_lock.release()
    noodle_lock.release()

    def eat2(name):
    chazi_lock.acquire()
    print('%s拿到了叉子'%name)
    noodle_lock.acquire()
    print('%s拿到了面条' %name)
    print('%s吃面'%name)
    noodle_lock.release()
    chazi_lock.release()


    Thread(target=eat1,args=('alex',)).start()
    Thread(target=eat2,args=('Egon',)).start()
    Thread(target=eat1,args=('nezha',)).start()
    Thread(target=eat2,args=('bossjin',)).start()

    多线程的时候虽然有全局解释性锁,GIL 的存在,,GIL锁的是线程,同一时间只有一个线程能访问CPU,但是当实现多线程的时候,如果数据有多把锁,
    但是由于CPU的时间片轮转法则,可能出现,多个线程拿了多个钥匙,不是一个一个线程拿了所有的钥匙,程序就会一直阻塞,这就是有名的死锁。
    上面的例子用的Lock()是互斥锁

    为了解决死锁问题,有了递归锁的出现,递归锁就像是一串钥匙,只能有一个人拿到所有钥匙,就不会出现死锁
    from threading import Thread,RLock

    chazi_lock = noodle_lock = RLock()
    def eat1(name):
    noodle_lock.acquire()
    print('%s拿到了面条'%name)
    chazi_lock.acquire()
    print('%s拿到了叉子'%name)
    print('%s吃面'%name)
    chazi_lock.release()
    noodle_lock.release()

    def eat2(name):
    chazi_lock.acquire()
    print('%s拿到了叉子'%name)
    noodle_lock.acquire()
    print('%s拿到了面条' %name)
    print('%s吃面'%name)
    noodle_lock.release()
    chazi_lock.release()


    Thread(target=eat1,args=('alex',)).start()
    Thread(target=eat2,args=('Egon',)).start()
    Thread(target=eat1,args=('nezha',)).start()
    Thread(target=eat2,args=('bossjin',)).start()
  • 相关阅读:
    Difference Between Performance Testing, Load Testing and Stress Testing
    什么是测试策略?
    性能测试和压力测试的区别
    测试工程师培训体系
    Java测试工具
    浅谈HTTP中Get与Post的区别
    Python 读书系列
    Automation- watin
    脚本语言&& Performance Testing
    HDFS分布式集群安装
  • 原文地址:https://www.cnblogs.com/bozhengheng/p/10310087.html
Copyright © 2020-2023  润新知