Whats the difference between std::condition_variable and std::condition_variable_any?

浪尽此生 提交于 2019-12-17 19:48:22

问题


I'm probably missing something obvious, but I can't see any difference between between std::condition_variable and std::condition_variable_any. Why do we need both?


回答1:


std::condition_variable is more specialized, and therefore can be more efficient when you don't need the flexibility of std::condition_variable_any.

From N3290 §30.5[thread.condition]/1

Class condition_variable provides a condition variable that can only wait on an object of type unique_lock<mutex>, allowing maximum efficiency on some platforms. Class condition_variable_any provides a general condition variable that can wait on objects of user-supplied lock types.

Actually, in LLVM's libc++, condition_variable_any is implemented using the more specialized condition_variable (which uses pthread_cond_t) on a shared_mutex.




回答2:


The difference is the parameter to the wait() functions. All the wait functions in std::condition_variable take a lock parameter of type std::unique_lock<std::mutex>&, whereas the wait functions for std::condition_variable_any are all templates, and take a lock parameter of type Lockable&, where Lockable is a template parameter.

This means that std::condition_variable_any can work with user-defined mutex and lock types, and with things like boost::shared_lock --- anything that has lock() and unlock() member functions.

e.g.

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);
    }
}

See the documentation for the just::thread implementation of the C++11 thread library for details:

std::condition_variable documentation

std::condition_variable_any documentation

or check out the latest public draft of the C++11 standard



来源:https://stackoverflow.com/questions/8758353/whats-the-difference-between-stdcondition-variable-and-stdcondition-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!