C++17: std::scoped_lock
C++17 includes an std::scoped_lock (defined in <mutex>) which basically replaces std::lock_guard. Both are RAII classes that automatically unlock a mutex when they are destroyed. The only difference between the two is that the new scoped_lock can handle multiple mutexes automatically, while lock_guard is limited to a single mutex.
Using the scoped_lock RAII class is straightforward. Here is an example:
std::mutex mutex1;
// ...
std::scoped_lock<std::mutex> sl(mutex1);
The scoped_lock class template is a variadic template supporting any number of mutexes:
std::mutex mutex1;
std::recursive_mutex mutex2;
// ...
std::scoped_lock<std::mutex, std::recursive_mutex> sl(mutex1, mutex2);
The declaration of the scoped_lock can be simplified thanks to C++17 template argument deduction for constructors:
std::mutex mutex1;
std::recursive_mutex mutex2;
// ...
std::scoped_lock sl(mutex1, mutex2);