用法:
先实例化 lock = threading.Lock()
1. lock.acquire() 上锁
需上锁代码
lock.release() 解锁
2. with lock: 上下两种方式都行
需上锁代码
整体代码:
import threading
lock = threading.Lock() 建立实例
a = 0
def func(n):
global a
for i in range(n):
lock.acquire() 上锁
a += 1
lock.release() 解锁
def func2(n):
global a
for i in range(n):
lock.acquire() 上锁
a -= 1
lock.release() 解锁
t1 = threading.Thread(target = func,args = (10000,))
t1.start()
t2 = threading.Thread(target = func,args = (10000,))
t2.start()
t1.join() 主进程等待
t2.join()
print(a)
图例: