【Python】死锁与递归锁

# ===================== 死锁 =====================
# from threading import Thread, Lock
# import time
#
# mutexA = Lock()
# mutexB = Lock()
#
# class MyThread(Thread):
# def run(self):
# self.f1()
# self.f2()
#
# def f1(self):
# mutexA.acquire()
# print('%s A' % self.name)
# mutexB.acquire()
# print('%s B' % self.name)
# mutexB.release()
# mutexA.release()
#
# def f2(self):
# mutexB.acquire()
# print('%s B' % self.name)
# time.sleep(0.1)
# mutexA.acquire()
# print('%s A' % self.name)
# mutexA.release()
# mutexB.release()
#
# if __name__ == '__main__':
# for i in range(10):
# t = MyThread()
# t.start()

# =====================互斥锁=====================
# 只可acquire一次
# from threading import Thread, Lock
#
# mutexA = Lock()
# mutexA.acquire()
# mutexA.acquire()
# mutexA.acquire()

# =====================递归锁=====================
# 支持acquire多次, 每acquire一次,计数器+1, 计数为0时, 其他线程方可用
from threading import Thread, RLock
import time

mutexB = mutexA = RLock()


class MyThread(Thread):
def run(self):
self.f1()
self.f2()

def f1(self):
mutexA.acquire()
print('%s A' % self.name)
mutexB.acquire()
print('%s B' % self.name)
mutexB.release()
mutexA.release()

def f2(self):
mutexB.acquire()
print('%s B' % self.name)
time.sleep(0.1)
mutexA.acquire()
print('%s A' % self.name)
mutexA.release()
mutexB.release()


if __name__ == '__main__':
for i in range(10):
t = MyThread()
t.start()
posted @ 2018-08-26 17:55  caya  阅读(136)  评论(0编辑  收藏  举报