要想在 Python3 中引入 Lock,调用 from threading import Lock
语句。Lock
类是Python中用于线程同步的一种机制,它可以确保在多线程环境下对共享资源德安全访问。
Lock
类提供了两个主要的方法:acquire()
和 release()
。acquire()
方法用于获取锁,如果锁处于被占用状态,则会阻塞线程直到获取到锁;release()
方法用于释放锁,将锁的状态设置为可用。
代码如下:
from threading import Thread, Lock
shared_resource = 0
lock = Lock()
def modify_shared_resource():
global shared_resource
lock.acquire()
try:
shared_resource += 1
print(f"shared_resource: {shared_resource}")
finally:
lock.release()
threads = []
for _ in range(5):
thread = Thread(target = modify_shared_resource)
threads.append(thread)
thread.start() # 启动一个线程
for t in threads:
t.join() # 等到线程 t 结束
print("All threads finished")
print(f"Final shared resource value: {shared_resource}")
# 结果如下
shared_resource: 1
shared_resource: 2
shared_resource: 3
shared_resource: 4
shared_resource: 5
All threads finished
Final shared resource value: 5
点个赞支持一下咯~