# 代码
# coding=utf-8
"""通过使用互斥锁,锁定全局变量,防止数据异常"""
import threading
num = 0
# 创建互斥锁
lock = threading.Lock()
def testOne():
global num
for i in range(100000):
# 在num加1前进行资源抢占,如果抢到则锁定资源,在num+1完成之后进行资源释放
lock.acquire() # 上锁
num += 1
lock.release()# 释放锁
print("testOne 执行完毕,num的值为:",num)
def testTwo():
global num
for i in range(100000):
lock.acquire()
num += 1
lock.release()
print("testTwo 执行完毕,num的值为:",num)
if __name__ == '__main__':
# 创建线程
t1 = threading.Thread(target=testOne)
t2 = threading.Thread(target=testTwo)
# 启动线程
t1.start()
t1.join()
t2.start()
t2.join()