Python中死锁的形成示例及死锁情况的防止
死锁示例 搞多线程的经常会遇到死锁的问题,学习操作系统的时候会讲到死锁相关的东西,我们用Python直观的演示一下。 死锁的一个原因是互斥锁。假设银行系统中,用户a试图转账100块给用户b,与此同时用户b试图转账200块给用户a,则可能产生死锁。 2个线程互相等待对方的锁,互相占用着资源不释放。 # coding=utf-8 import time import threading class Account: def __init__ (self, _id, balance, lock): self.id = _id self.balance = balance self.lock = lock def withdraw(self, amount): self.balance -= amount def deposit(self, amount): self.balance += amount def transfer(_from, to, amount): if _from.lock.acquire(): # 锁住自己的账户 _from.withdraw(amount) time.sleep( 1) # 让交易时间变长,2个交易线程时间上重叠,有足够时间来产生死锁 print ' wait for lock... ' if to.lock.acquire(): #