码迷,mamicode.com
首页 > 编程语言 > 详细

用python演示一种死锁的产生

时间:2014-10-07 20:38:43      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:多线程   操作系统   死锁   

搞多线程的经常会遇到死锁的问题,学习操作系统的时候会讲到死锁相关的东西,我们用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():#锁住对方的账户
            to.deposit(amount)
            to.lock.release()
        _from.lock.release()
    print 'finish...'

a = Account('a',1000, threading.Lock())
b = Account('b',1000, threading.Lock())
threading.Thread(target = transfer, args = (a, b, 100)).start()
threading.Thread(target = transfer, args = (b, a, 200)).start()


用python演示一种死锁的产生

标签:多线程   操作系统   死锁   

原文地址:http://blog.csdn.net/handsomekang/article/details/39855759

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!