一、使用锁实现同步
1. Lock锁
import threading
import time
from threading import Lock,RLock #可重入的锁
#1.用锁会影响性能,获取锁和释放锁都需要一定时间
#2.用锁可能会引起死锁
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__":
start_time = time.time()
thread1 = threading.Thread(target=add)
thread2 = threading.Thread(target=desc)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(total)
end_time = time.time()
print("cost time:", end_time-start_time)
运行结果:

2. RLock锁

本文详细介绍了Python中实现多线程同步的三种方式:使用Lock和RLock进行基本同步,通过Condition变量实现复杂线程同步,以及利用Semaphore信号量进行线程间同步。通过实例展示了如何在多线程环境下确保数据的一致性和程序的正确执行。

1166

被折叠的 条评论
为什么被折叠?



