chmike chmike - 1 year ago 90
C++ Question

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

I have two use cases.

A. I want to synchronise access by two threads to a queue.

B. I want to synchronise access by two threads to a queue and use a condition variable because one of the threads will wait on content to be stored into the queue by the other thread.

For use case A I see code example using

. For use case B I see code example using

What is the difference between the two and which one should I use in which use case?

inf inf
Answer Source

The difference is that you can lock and unlock a std::unique_lock. std::lock_guard will be locked only once on construction and unlocked on destruction.

So for usecase B you definitely need a std::unique_lock for the condition variable. In case A it depends whether you need to relock the guard.

std::unique_lock has other features that allow it to e.g.: be constructed without locking the mutex immediately but to build the RAII wrapper (see here).

Lock guards can be used when you simply need a wrapper for a limited scope, e.g.: a member function:

void member_foo() {
    std::lock_guard<mutex_type> lock(this->my_mutex);

To clarify a question by chmike, by default std::lock_guard and std::unique_lock are the same. So in the above case, you could replace std::lock_guard with std::unique_lock. However, std::unique_lock might have a tad more overhead.