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

标签 python multithreading python-2.7 synchronization locking

我在这里看到以下代码: 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.

最佳答案

notify()和notifyAll()方法不会释放锁;这意味着被唤醒的一个或多个线程不会立即从其 wait() 调用中返回,而是仅在调用 notify() 或 notifyAll() 的线程最终放弃锁的所有权时才返回。

来源:https://docs.python.org/2.7/library/threading.html#condition-objects

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

相关文章:

python PyQt : Is it possible to use QThread with a non-GUI program?

python - 有问题的值(value)观

python - 用新创建的对象 ID 替换复杂数据结构中的对象 ID

python - 线程顺序循环还是并发循环?

python - 如何根据第二个索引列表重新排列一个列表

python - 在函数式编程(或其他方式)中递归时,使用显式状态变量的好处/限制是什么?

python - 特定列中的简单 Numpy 最小值和最大值

python - 单元测试: wxpython's event method raises exception but assertRaises does not detect it

c++ - 对 Vector 的多线程、只读访问。复制还是锁定?

java - 中断 hibernate 线程