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
无影响
"""
posted @ 2019-02-02 21:02  roccoshi  阅读(184)  评论(0编辑  收藏  举报