std :: lock_guard还是std :: scoped_lock?

问题描述:

C ++ 17引入了一个名为 std::scoped_lock 的新锁类. >.

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

从文档来看,它看起来与已经存在的std::lock_guard类相似.

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

有什么区别,什么时候应该使用?

What's the difference and when should I use it?

唯一的重要区别是std::scoped_lock具有可变参数的构造函数,该构造函数使用多个互斥量.这样可以以死锁的方式锁定多个互斥锁,从而避免使用std::lock的情况.

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

以前,您必须按照附加的范围锁使它更易于使用,并避免了相关的错误.您可以考虑弃用std::lock_guard. std::scoped_lock的单参数情况可以实现为一种特殊化,因此您不必担心可能的性能问题.

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已经支持std::scoped_lock,可以在此处看到.

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