gpt4 book ai didi

python - 通知后和条件锁定释放前会发生什么

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:49 27 4
gpt4 key购买 nike

我在这里看到以下代码: https://docs.python.org/2/library/threading.html#condition-objects

# Consume one item (thread 1)
cv.acquire()
while not an_item_is_available():
cv.wait()
get_an_available_item()
cv.release()

# Produce one item (thread 2)
cv.acquire()
make_an_item_available()
cv.notify()
cv.release()

我的问题是,当在线程 2 中调用 cv.notify() 时,线程 1 从 cv.wait() 中唤醒,但在线程 2 调用之前cv.release(),线程 1 没有获取锁(我说的对吗?)..我的问题是:调用 cv.notify()< 后线程 1 的行为是什么 并在从线程 2 调用 cv.release() 之前?

更新:

我从 https://stackoverflow.com/a/17337630/1497720 找到了, 但它用于 java:

This maintains two datastructures - a wait set and an entry set. Waiting threads are added to the wait set and parked whereas threads attempting to take the monitor are added to the entry set and then parked. On notify a thread is taken from the wait set and added to the entry set. When a thread releases the lock it unparks a thread from the entry set if there is one. Note that these sets are actually implemented as queues (linked lists) so are treated on a FIFO basis.

最佳答案

来自 Condition.notify 的文档:

Note: an awakened thread does not actually return from its wait() call until it can reacquire the lock. Since notify() does not release the lock, its caller should.

因此,调用 cv.notify() 之后但调用 cv.release() 之前的行为是线程 1 仍然阻塞在 cv.wait ()

关于python - 通知后和条件锁定释放前会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26553311/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com