银行转账:两个账户同时给对方转账,模拟线程死锁
from threading import Thread,Lock
from time import sleep
#账户类
class Account:
def __init__(self,_id,balance,lock): #每个账户自带一个锁,只要数字balance要变动,就要提前上锁
self.id = _id
self.balance = balance
self.lock = lock
#取钱
def withdraw(self,amount):
self.balance -= amount
#存钱
def deposit(self,amount):
self.balance += amount
#查看余额
def get_balance(self):
return self.balance
#生成两个账户
Tom = Account('Tom',12000,Lock()) #Lock()直接创建了一个锁
Abby = Account('Abby',9000,Lock())
#转账函数,转账基本原则:谁的账户要动,需要先上锁
#from_参数为要转出账户,to参数为转入账户
def transfer(from_,to,amount):
#from_账户上锁
if from_.lcok.acquire():
from_.withdraw(amount) #from_账户减少
#to账户要动了,也要上锁
if to.lock.acquire():
to.deposit(amount) #to 加钱
to.lock.release() #加钱完毕,解锁
#from_账户也转账完毕,解锁
from_.lock.release()
print('%s给%s转了%d元' %(from_._id,to._id,amount)
#生成两个线程,同时转账
t1 = Thread(target=transfer,args=(Tom,Abby,4000)) #Tom给Abby转4000
t2 = Thread(target=transfer,args=(Abby,Tom,1500)) #Abby给Tom转2500
#流程:两个线程同时执行,线程t1给Tom上锁,线程t2给Abby上锁,两个线程都向下走,准备给对方上锁,发现对方已经锁上了,资源互不释放,造成死锁
t1.start()
t2.start()
t1.join()
t2.join()
print('Tom:',Tom.get_balance())
print('Abby:',Abby.get_balance())
来源:CSDN
作者:俞泰鑫
链接:https://blog.csdn.net/god_yutaixin/article/details/103460963