condition.wait() 在 "with" 块或 self.acquire 和 self.release 中?
condition.wait() in a "with" block or self.acquire and self.release?
使用条件变量时,使用 with
语句是否是一种不好的做法?
我知道 condition.wait()
释放了锁,但是如果在 with
块中调用它,这种行为会改变吗?
class BlockingQueue:
def __init__(self, size):
self.max_size = size
self.queue = deque()
self.condition = Condition()
# if there are already x items in queue, should block
def enqueue(self, item):
with self.condition:
while len(self.queue) == self.max_size:
self.condition.wait()
self.queue.append(item)
self.condition.notify_all()
Condition
对象 documentation 部分表示:
A condition variable obeys the context management protocol: using the with
statement acquires the associated lock for the duration of the enclosed block. The acquire()
and release()
methods also call the corresponding methods of the associated lock.
所以,是的,它们在 with
语句中工作得很好。事实上,这是使用它们的首选方式。
使用条件变量时,使用 with
语句是否是一种不好的做法?
我知道 condition.wait()
释放了锁,但是如果在 with
块中调用它,这种行为会改变吗?
class BlockingQueue:
def __init__(self, size):
self.max_size = size
self.queue = deque()
self.condition = Condition()
# if there are already x items in queue, should block
def enqueue(self, item):
with self.condition:
while len(self.queue) == self.max_size:
self.condition.wait()
self.queue.append(item)
self.condition.notify_all()
Condition
对象 documentation 部分表示:
A condition variable obeys the context management protocol: using the
with
statement acquires the associated lock for the duration of the enclosed block. Theacquire()
andrelease()
methods also call the corresponding methods of the associated lock.
所以,是的,它们在 with
语句中工作得很好。事实上,这是使用它们的首选方式。