from threading import Thread
from threading import Lock
g_num = 0
def work1():
global g_num
for i in range(1000000):
mutex.acquire()#加锁
g_num+=1
mutex.release()#解锁
def work2():
global g_num
for i in range(1000000):
mutex.acquire()#加锁
g_num+=1
mutex.release()#解锁
mutex = Lock()#创建锁
if __name__ == '__main__':
# work1()
# work2()
# print('g_num:',g_num)#2000000
t1 = Thread(target=work1)
t2 = Thread(target=work2)
t1.start()
t2.start()
t1.join()
t2.join()
print('g_num:', g_num)
线程非安全
最新推荐文章于 2022-08-20 16:02:46 发布