等待多个互斥锁的条件变量
Condition variable waiting on multiple mutexes
我有一个等待自定义锁的 std::condition_variable_any
,它由两个互斥体(一个 std::mutex
和一个共享锁 std::shared_mutex
)组成。它的 unlock()
操作简单地按顺序解锁两个互斥量。
例如(伪代码):
mutex mutex1;
shared_mutex mutex2;
condition_variable_any cv;
// acquiring the locks
DualLock lock(unique_lock(mutex1), shared_lock(mutex2));
// waiting
cv.wait(lock);
cv.wait()
应该自动 解锁 mutex1
和 mutex2
,并让线程休眠直到 cv
收到通知.
一旦mutex1
或mutex2
中的任何一个被解锁,它仍然保证线程正在休眠并监听条件变量通知?
或者是否有可能一个互斥锁被解锁,第二个线程锁定它,发送通知,但是第一个线程还没有休眠和监听。所以通知从未到达,也没有发生唤醒。
如果DualLock
满足BasicLockable
的要求,那么代码将按预期执行。没有就不会。
BasicLockable 引用是 here
So the notification never arrived and no wakeup occurs.
如果条件变量使用得当,这种情况永远不会发生。条件变量的唤醒不能解释为事件信号,因为 condition_variable 的文档解释说可能存在虚假唤醒。
充其量,该通知表明现在可能是测试您正在等待的条件的好时机(您可以在确信测试受互斥锁保护的情况下这样做)。
条件的状态和当前线程的阻塞状态是两个独立的问题。
这是一个更好的例子(假设 DualLock 模型 BasicLockable 正确):
bool condition_met = false;
mutex mutex1;
shared_mutex mutex2;
condition_variable_any cv;
// acquiring the locks
DualLock lock(unique_lock(mutex1), shared_lock(mutex2));
while(!condition_met)
{
// waiting
cv.wait(lock);
}
// whatever happens, you have the lock here
// ...work
lock.unlock();
您的通知者会这样通知:
DualLock lock(unique_lock(mutex1), shared_lock(mutex2));
condition_met = true;
lock.unlock(); // note the order: unlock mutex first...
cv.notify_all(); // ...then notify the condition variable
我有一个等待自定义锁的 std::condition_variable_any
,它由两个互斥体(一个 std::mutex
和一个共享锁 std::shared_mutex
)组成。它的 unlock()
操作简单地按顺序解锁两个互斥量。
例如(伪代码):
mutex mutex1;
shared_mutex mutex2;
condition_variable_any cv;
// acquiring the locks
DualLock lock(unique_lock(mutex1), shared_lock(mutex2));
// waiting
cv.wait(lock);
cv.wait()
应该自动 解锁 mutex1
和 mutex2
,并让线程休眠直到 cv
收到通知.
一旦mutex1
或mutex2
中的任何一个被解锁,它仍然保证线程正在休眠并监听条件变量通知?
或者是否有可能一个互斥锁被解锁,第二个线程锁定它,发送通知,但是第一个线程还没有休眠和监听。所以通知从未到达,也没有发生唤醒。
如果DualLock
满足BasicLockable
的要求,那么代码将按预期执行。没有就不会。
BasicLockable 引用是 here
So the notification never arrived and no wakeup occurs.
如果条件变量使用得当,这种情况永远不会发生。条件变量的唤醒不能解释为事件信号,因为 condition_variable 的文档解释说可能存在虚假唤醒。
充其量,该通知表明现在可能是测试您正在等待的条件的好时机(您可以在确信测试受互斥锁保护的情况下这样做)。
条件的状态和当前线程的阻塞状态是两个独立的问题。
这是一个更好的例子(假设 DualLock 模型 BasicLockable 正确):
bool condition_met = false;
mutex mutex1;
shared_mutex mutex2;
condition_variable_any cv;
// acquiring the locks
DualLock lock(unique_lock(mutex1), shared_lock(mutex2));
while(!condition_met)
{
// waiting
cv.wait(lock);
}
// whatever happens, you have the lock here
// ...work
lock.unlock();
您的通知者会这样通知:
DualLock lock(unique_lock(mutex1), shared_lock(mutex2));
condition_met = true;
lock.unlock(); // note the order: unlock mutex first...
cv.notify_all(); // ...then notify the condition variable