抄的视频代码做的测试,代码如下?
#coding:utf-8
import threading
import time
lock = threading.Lock()
class Myaccount:
def __init__(self,balance):
self.balance =balance
def draw(account,amount):
if account.balance >= amount:
#time.sleep(0.1)
account.balance-=amount
#print '取钱成功,余额为:',account.balance
print threading.currentThread().name,'取钱成功,余额为::',account.balance
else:
print threading.currentThread().name,'取钱失败------------,余额:',account.balance
def main():
while True:
account = Myaccount(1000)
ta = threading.Thread(name="ta",target=draw,args=(account,800))
tb = threading.Thread(name= "tb",target=draw, args=(account, 800))
ta.start()
tb.start()
#ta.join()
#tb.join()
if __name__ == '__main__':
main()
按原理将,在没设置线程安全锁时,是可能线程相互串行了,导致用户存款扣除800后,会再扣除800,于是余额为-600
但是,进行了大量测试,发现压根无法出现-600的情况。。。
不过按照视频说的,在线程中使用了timel.sleep方法,将会导致线程串行,会导致出现-600的情况:
下面为使用线程锁的代码(使用了with lock):
#coding:utf-8
import threading
import time
lock = threading.Lock()
class Myaccount:
def __init__(self,balance):
self.balance =balance
def draw(account,amount):
with lock:
if account.balance >= amount:
time.sleep(0.1)
account.balance-=amount
print threading.currentThread().name,'取钱成功,余额为::',account.balance
else:
print threading.currentThread().name,'取钱失败------------,余额:',account.balance
def main():
while True:
account = Myaccount(1000)
ta = threading.Thread(name="ta",target=draw,args=(account,800))
tb = threading.Thread(name= "tb",target=draw, args=(account, 800))
ta.start()
tb.start()
#ta.join()
#tb.join()
if __name__ == '__main__':
main()