zoukankan      html  css  js  c++  java
  • 线程锁,

    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()
  • 相关阅读:
    SQL 基础命令和函数
    [Delphi] FMXUI
    Win10 磁盘占用 100% 有效解决办法
    [转] Windows下编译OpenSSL
    [Java] Spring + SpringMVC + Maven + JUnit 搭建
    [Java] ApplicationContext 辅助类
    [Java] Maven 镜像仓库
    [Java] Spring MVC 知识点
    [Java] Maven 建立 Spring MVC 工程
    [Java] Maven 安装和配置
  • 原文地址:https://www.cnblogs.com/bozhengheng/p/10310087.html
Copyright © 2011-2022 走看看