我可能遗漏了一些明显的东西,但我看不出 std::condition_variable
和 std::condition_variable_any
之间有任何区别。为什么我们都需要?
最佳答案
区别在于wait()
的参数。功能。 std::condition_variable
中的所有等待函数获取 std::unique_lock<std::mutex>&
类型的锁定参数,而 std::condition_variable_any
的等待函数都是模板,并采用 Lockable&
类型的锁定参数, 其中 Lockable
是一个模板参数。
这意味着 std::condition_variable_any
可以使用用户定义的互斥锁和锁类型,以及像 boost::shared_lock
这样的东西--- 任何有 lock()
和 unlock()
成员函数。
例如
std::condition_variable_any cond;
boost::shared_mutex m;
void foo() {
boost::shared_lock<boost::shared_mutex> lk(m);
while(!some_condition()) {
cond.wait(lk);
}
}
从 C++20 开始,condition_variable_any
还支持新 jthread 类的停止标记。这意味着如果您有这种类型的条件变量,如果发出停止请求,它将放弃互斥锁,而无需编写额外的轮询代码。此功能不适用于 condition_variable
由于某些技术原因导致“竞争、死锁和未定义的行为”。
void testInterruptibleCVWait()
{
bool ready = false;
std::mutex readyMutex;
std::condition_variable_any readyCV;
std::jthread t([&ready, &readyMutex, &readyCV] (std::stop_token st)
{
while (...)
{
...
{
std::unique_lock lg{readyMutex};
readyCV.wait_until(lg, [&ready] {return ready; }, st);
// also ends wait on stop request for st
}
...
}
});
...
} // jthread destructor signals stop request and therefore unblocks the CV wait and ends the started thread
详见文档:
std::condition_variable
documentation
std::condition_variable_any
documentation并具体查看wait
, wait_for
和 wait_until
现在支持 jthread 上的停止请求的成员函数。
关于c++ - std::condition_variable 和 std::condition_variable_any 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8758353/