在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ 為什么當(dāng)進(jìn)程執(zhí)行if語句里面lock.acquire()失敗時不會跳出if,而是

為什么當(dāng)進(jìn)程執(zhí)行if語句里面lock.acquire()失敗時不會跳出if,而是一直等待鎖的釋放

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個交易線程時間上重疊,有足夠時間來產(chǎn)生死鎖 
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()

當(dāng)進(jìn)程執(zhí)行if語句里面lock.acquire()時會一直等待鎖的釋放嗎,為什么lock.acquire()失敗時不會跳過if執(zhí)行后面的語句?

回答
編輯回答
別硬撐
Lock.acquire([ blocking ] )
獲取鎖定,阻止或不阻止。
當(dāng)調(diào)用阻塞參數(shù)設(shè)置為True(默認(rèn))時,阻塞,直到鎖定解鎖,然后將其設(shè)置為鎖定并返回True。
當(dāng)調(diào)用阻塞參數(shù)設(shè)置為False,不要阻塞。如果阻塞設(shè)置的呼叫True會阻塞,F(xiàn)alse 立即返回; 否則,將鎖設(shè)置為鎖定并返回True。

所以你可以寫成 if _from.lock.acquire(False): 不阻塞

參考https://docs.python.org/2.7/l...

2017年9月5日 10:50