"""
线程锁的意义,让一个线程从头到尾的执行
阻止了多线程的并发执行,包含锁的某段代码只能以单线程模式执行,效率降低
在需要的时候上锁
"""
import threading
lock = threading.Lock()
num = 10
def run(n):
global num
for i in range(1000000):
''' try:
# 上锁
lock.acquire()
num = num - n
num = num + n
finally:
# 释放
lock.release()'''
with lock:
num = num - n
num = num + n
# 两种方式效果相同,with lock 可以自动上锁与解锁
if __name__ == '__main__':
t1 = threading.Thread(target=run, args=(6,))
t2 = threading.Thread(target=run, args=(9,))
t1.start()
t2.start()
t1.join()
t2.join()
print('num', num)