Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::lock_guard or std::scoped_lock?

People also ask

What is std :: Scoped_lock?

std::scoped_lock The class scoped_lock is a mutex wrapper that provides a convenient RAII-style mechanism for owning one or more mutexes for the duration of a scoped block. When a scoped_lock object is created, it attempts to take ownership of the mutexes it is given.

What is std :: lock_guard?

std::lock_guard The class lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block. When a lock_guard object is created, it attempts to take ownership of the mutex it is given.

What is the difference between unique_lock and lock_guard?

A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.

Does std :: lock_guard block?

No. The critical section begins at the point of declaration of the guard. The guard is declared after the condition - so it is not guarded. If you need the condition to be guarded as well, then move the guard before the if statement.


The scoped_lock is a strictly superior version of lock_guard that locks an arbitrary number of mutexes all at once (using the same deadlock-avoidance algorithm as std::lock). In new code, you should only ever use scoped_lock.

The only reason lock_guard still exists is for compatibility. It could not just be deleted, because it is used in current code. Moreover, it proved undesirable to change its definition (from unary to variadic), because that is also an observable, and hence breaking, change (but for somewhat technical reasons).


The single and important difference is that std::scoped_lock has a variadic constructor taking more than one mutex. This allows to lock multiple mutexes in a deadlock avoiding way as if std::lock were used.

{
    // safely locked as if using std::lock
    std::scoped_lock<std::mutex, std::mutex> lock(mutex1, mutex2);     
}

Previously you had to do a little dance to lock multiple mutexes in a safe way using std::lock as explained this answer.

The addition of scope lock makes this easier to use and avoids the related errors. You can consider std::lock_guard deprecated. The single argument case of std::scoped_lock can be implemented as a specialization and such you don't have to fear about possible performance issues.

GCC 7 already has support for std::scoped_lock which can be seen here.

For more information you might want to read the standard paper


Late answer, and mostly in response to:

You can consider std::lock_guard deprecated.

For the common case that one needs to lock exactly one mutex, std::lock_guard has an API that is a little safer to use than scoped_lock.

For example:

{
   std::scoped_lock lock;  // protect this block
   ...
}

The above snippet is likely an accidental run-time error because it compiles and then does absolutely nothing. The coder probably meant:

{
   std::scoped_lock lock{mut};  // protect this block
   ...
}

Now it locks/unlocks mut.

If lock_guard was used in the two examples above instead, the first example is a compile-time error instead of a run-time error, and the second example has identical functionality as the version which uses scoped_lock.

So my advice is to use the simplest tool for the job:

  1. lock_guard if you need to lock exactly 1 mutex for an entire scope.

  2. scoped_lock if you need to lock a number of mutexes that is not exactly 1.

  3. unique_lock if you need to unlock within the scope of the block (which includes use with a condition_variable).

This advice does not imply that scoped_lock should be redesigned to not accept 0 mutexes. There exist valid use cases where it is desirable for scoped_lock to accept variadic template parameter packs which may be empty. And the empty case should not lock anything.

And that's why lock_guard isn't deprecated. scoped_lock and unique_lock may be a superset of functionality of lock_guard, but that fact is a double-edged sword. Sometimes it is just as important what a type won't do (default construct in this case).


Here is a sample and quote from C++ Concurrency in Action:

friend void swap(X& lhs, X& rhs)
{
    if (&lhs == & rhs)
        return;
    std::lock(lhs.m, rhs.m);
    std::lock_guard<std::mutex> lock_a(lhs.m, std::adopt_lock);
    std::lock_guard<std::mutex> lock_b(rhs.m, std::adopt_lock);
    swap(lhs.some_detail, rhs.some_detail);
}

vs.

friend void swap(X& lhs, X& rhs)
{
    if (&lhs == &rhs)
        return;
    std::scoped_lock guard(lhs.m, rhs.m);
    swap(lhs.some_detail, rhs.some_detail);
}

The existence of std::scoped_lock means that most of the cases where you would have used std::lock prior to c++17 can now be written using std::scoped_lock, with less potential for mistakes, which can only be a good thing!