Why does std::condition_variable take a std::unique_lock instead of a std::mutex? -- StackOverflow

Recently on StackOverflow, someone asked: What's the job of std::unique_lock when used with std::condition_variable::wait()?

A more detailed answer is available in this earlier question, including why taking a unique_lock makes the C++ version superior to some other libraries' designs:

C++11: Why does std::condition_variable use std::unique_lock?

I am a bit confused about the role of std::unique_lock when working with std::condition_variable. As far as I understood the documentation, std::unique_lock is basically a bloated lock guard, with the possibility to swap the state between two locks.

I've so far used pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) for this purpose (I guess that's what the STL uses on posix). It takes a mutex, not a lock.

What's the difference here? Is the fact that std::condition_variable deals with std::unique_lock an optimization? If so, how exactly is it faster?

 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.