import threading
from threading import Lock
import time
"""
使用以下加锁方式
with 锁对象:
do something
和以下方式一样的效果
lock.acquire()
try:
do something
finnaly:
lock.release()
"""
# 此方法加锁,正常执行
def demo_one():
time.sleep(1)
with lock:
global num
num -= 1
print("locked" + str(num))
time.sleep(1)
time.sleep(2)
# 此方法不加锁,100个线程会全部输出 -100
# def demo_one():
# global num
# time.sleep(1)
# num -= 1
# time.sleep(1)
# print("locked" + str(num))
if __name__ == '__main__':
lock = Lock()
num = 0
for i in range(100):
t = threading.Thread(target=demo_one)
t.start()
Python threading with自动加锁解锁
最新推荐文章于 2023-12-09 19:00:00 发布
本文介绍了如何使用Python的`threading.Lock`实现线程同步,通过`with`语句和显式`acquire()`/`release()`方法,确保在多线程环境下变量操作的正确性。通过对比未加锁的并发问题,展示了加锁在避免数据竞争上的重要性。
摘要由CSDN通过智能技术生成