账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    为什么当进程执行if语句里面lock.acquire()失败时不会跳出if,而是一直等待锁的释放
    32
    0

    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()

    当进程执行if语句里面lock.acquire()时会一直等待锁的释放吗,为什么lock.acquire()失败时不会跳过if执行后面的语句?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部