问下这段代码错误在哪里?
import threading
import time
balance = 100
lock = threading.Lock()
lock2 = threading.Lock()
def add(n):
lock2.acquire()
try:
global balance
balance += n
print(balance)
finally:
lock2.release()
#print(balance)
return balance
def mins(n):
lock.acquire()
try:
global balance
balance -= n
finally:
lock.release()
print(balance)
return balance
'''
def change(n):
add(n)
mins(n)
print('n: {}, balance:{}'.format(n,balance))
'''
class threadTest(threading.Thread):
lock = threading.Lock()
def __init__(self,number,*args,**kwargs):
super().__init__(*args,**kwargs)
self.number = number
def run(self):
i = 0
for i in range(10):
self.lock.acquire()
try:
n = add(self.number)
print('add({}): balance:{}'.format(i,n))
i += 1
finally:
self.lock.release()
class threadTest2(threading.Thread):
lock = threading.Lock()
def __init__(self,number,*args,**kwargs):
super().__init__(*args,**kwargs)
self.number = number
def run(self):
i = 0
for i in range(10):
self.lock.acquire()
try:
n = mins(self.number)
print('mins({}): balance:{}'.format(i,n))
i += 1
finally:
self.lock.release()
if __name__ == '__main__':
t = threadTest(1)
t3 = threadTest2(5)
t1 = threadTest(5)
t2 = threadTest2(1)
t.start()
t1.start()
t2.start()
t3.start()
'''
i = 0
while i < 10:
add(10)
mins(10)
i += 1
'''
老师问下这段代码的错误在哪里。。我不是已经锁住了么,每次运行到最后打印出来的结果也是balance不变,但是程序内储存的结果balance每次都会变化,这是为什么呢?
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 2727 份
- 解答问题 8160 个
想要进入Python Web、爬虫、人工智能等高薪领域,你需要掌握本阶段的Python基础知识,课程安排带你高效学习轻松入门,学完你也能听得懂Python工程师的行业梗。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星