多线程的Lock和RLock 以及什么情况会造成死锁

# coding: utf-8  编程锁
# 可重入的锁RLock
# 在同一个线程里面, 可以连续多次调用acquire  一定要注意acquire 和 release的次数必须相同
import threading
from threading import Lock


total = 0
lock = Lock()


def add():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()  # 获取锁
        total += 1
        lock.release()  # 释放锁


def desc():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()  # 获取锁
        total -= 1
        lock.release()  # 释放锁


if __name__ == '__main__':
    thread1 = threading.Thread(target=add)
    thread2 = threading.Thread(target=desc)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print(total)

# 1.用锁会影响性能
# 2.锁会造成死锁
#  死锁的情况 A(a, b)    第二种情况我们写了两个acquire(a)acquire(a)会造成死锁 连续acquire两次
"""
A(a, b)   # A先得到a加锁 B先得到b加锁 A没获取到b不会释放a  B没获取到a不会释放b  造成死锁  互相等待
acquire(a)
acquire(b)

B(a, b)
acquire(b)
acquire(a)
"""

推荐阅读更多精彩内容