• 2019-02-02 Python学习之死锁和Rlock


    死锁:“当一个线程永远地持有一个锁,并且其他线程都尝试去获得这个锁时,那么它们将永远被阻塞”

    e.g.

    import threading
    import time
    
    mutexboy = threading.Lock()
    mutexgirl = threading.Lock()
    
    class boy(threading.Thread):
        def run(self):
            if mutexboy.acquire(1):#锁定成功继续执行,不成功一直等待
                print("boy say i am sorry     up")
                time.sleep(1)
                if mutexgirl.acquire(1):
                    print("girl say i am sorry      down")
                mutexboy.release()
    
    
    class girl(threading.Thread):
        def run(self):
            if mutexgirl.acquire(1):
                print("girl say i am sorry      up")
                if mutexboy.acquire(1):
                    print("boy say i am sorry     down")
                mutexgirl.release()
    
    #当一对情侣都不先道歉时造成死锁
    
    boy1 = boy()
    boy1.start()
    girl1 = girl()
    girl1.start()
    
    #结果:
    #boy say i am sorry     up
    #girl say i am sorry      up
    #然后程序走不动了
    

    Rlock的用处

    避免单线程死锁,即一个线程反复加锁问题

    import threading
    
    num=0
    #mutex = threading.Lock()    #这样单线程会死锁------------(1)
    mutex = threading.RLock()    #Rlock可以避免单线程死锁-----------(2)
    
    class Mythread(threading.Thread):
        def run(self):
            global num
            if mutex.acquire(1):
                num=num+1
                print(self.name,num)
                if mutex.acquire(1):
                     num=num+1000
                     mutex.release()
                mutex.release()
    
    for i in range(5):# 开启五个线程
        t = Mythread()
        t.start()
    """
    1->
    Thread-1 1 之后锁死
    
    
    2->
    Thread-1 1
    Thread-2 1002
    Thread-3 2003
    Thread-4 3004
    Thread-5 4005
    无影响
    """
    
  • 相关阅读:
    python3使用PyMysql连接mysql数据库
    MySQL知识总结
    python--正则表达式
    python之多线程
    python在windows和linux环境的进程对比及进程和进程之间的通信
    python基础之生成器(generator)
    python基础之动态添加属性和方法
    [STM32F1] 【转】STM32驱动MPU6050
    51单片机怎么使用MPU6050读取角度值程序 ??
    stm32f10x_lib.h
  • 原文地址:https://www.cnblogs.com/roccoshi/p/13027102.html
Copyright © 2020-2023  润新知