std::lock_guard or std::scoped_lock?

前端 未结 4 799
说谎
说谎 2020-11-27 10:35

C++17 introduced a new lock class called std::scoped_lock.

Judging from the documentation it looks similar to the already existing std::lock_guard clas

4条回答
  •  一向
    一向 (楼主)
    2020-11-27 10:59

    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 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

提交回复
热议问题