互斥锁
(ps:仅有代码,小伙伴们利用百度,冲啊!!!)
#coding=utf-8
"""
使用线程同步与互斥锁的情况
多线程访问同一资源
增加取锁跟释放锁
"""
from threading import Thread, Lock
from time import sleep
class Account:
def __init__(self,money,name):
self.money = money
self.name = name
# 模拟取钱
class Drawing(Thread):
def __init__(self,drawingNum,account):
Thread.__init__(self)
self.drawingNum = drawingNum
self.account = account
self.expenseTotal = 0
def run(self):
lock1.acquire()
if self.account.money < self.drawingNum:
print("余额不足!")
return
sleep(1) # 测试发生冲突
self.account.money -= self.drawingNum
self.expenseTotal += self.drawingNum
lock1.release()
print(f"账户:{self.account.name},余额是:{self.account.money}")
print(f"账户:{self.account.name},总共取了:{self.expenseTotal}")
if __name__ == '__main__':
a1 = Account(1000,"ltr")
lock1 = Lock()
draw1 = Drawing(80,a1)
draw2 = Drawing(80,a1)
draw1.start()
draw2.start()