抄的视频代码做的测试,代码如下?
#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()


![[python] AES-GCM加解密函数-微慑信息网-VulSee.com](https://vulsee.com/wp-content/uploads/2024/12/4a3de68ff9eca0a01bae73a7470170f3.png)


![[python]文本处理-微慑信息网-VulSee.com](https://vulsee.com/wp-content/uploads/2023/12/e036ea90943d8195df3aa3e2ad3db122.png)
![[python] 输出颜色 - colorama / termcolor [补充]-微慑信息网-VulSee.com](https://vulsee.com/wp-content/uploads/2023/10/3ce37224d46fae3bee75b135ba129c77.png)
![[vulsee.com] 使用openpyxl 读取xlsx中的网址链接-微慑信息网-VulSee.com](https://vulsee.com/wp-content/uploads/2023/06/92d3798abeb4baabf03ebcf81d50e73e.png)




![[八卦] 王婷婷—揭秘一个大三女生的性爱录像-微慑信息网-VulSee.com](http://free.86hy.com/crack/pic/1.jpg)
![[随笔]今天国际警察节-微慑信息网-VulSee.com](http://photo.sohu.com/20041017/Img222528326.jpg)

青云网
