多线程回顾-线程同步RLock,Lock

import threading
from threading import Lock,RLock#可重入的锁
# 全局解释器锁 GIL
# 非常影响性能,死锁(Lock不能同时两个acquire),调用使用锁的其他函数
# Rlock 在一个线程中,可以连续多次调用acquire,但注意release次数要匹配
#
# lock = Lock()
lock = RLock() # 实际开发中使用次数多
total = 0

# def add():
#     global total
#     with lock: # 方法1
#         for i in range(10000000):
#             total +=1

def add():
    global total
    global lock
    for i in range(10000000):
        lock.acquire()
        lock.acquire()
        total +=1
        lock.release()
        lock.release()
def desc():
    global total
    global lock
    for i in range(10000000):
        lock.acquire()
        total -= 1
        lock.release()
thread1 = threading.Thread(target=add)
thread2 = threading.Thread(target=desc)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

print(total)
# 167499
# 1518478
发布了80 篇原创文章 · 获赞 0 · 访问量 1866

猜你喜欢

转载自blog.csdn.net/qq_37463791/article/details/105028017