What's the best way to lock multiple std::mutex'es?

Note: This question concerns C++11. The answer to the same question in C++17 (or later revisions) may have changed. For details:

  • std::lock_guard or std::scoped_lock?

When we want to lock multiple std::mutex'es, we use std::lock(). But std::lock() does not provide RAII feature.

When we want to lock a std::mutex in RAII way, we use std::lock_guard. But std::lock_guard cannot lock multiple std::mutex'es safely.

Is there any way to take the advantages of both methods, to lock multiple std::mutex'es in RAII way?


Yes, you can use a std::unique_lock with std::defer_lock. It tells the unique_lock to not lock the mutex immediately, but to build the RAII wrapper.

std::unique_lock<std::mutex> lk1(mutex1, std::defer_lock);
std::unique_lock<std::mutex> lk2(mutex2, std::defer_lock);
std::lock(lk1, lk2);

Due to its variadic nature std::lock is not bound to only two arguments but can be used with as many arguments as your compiler has support for.

Howard Hinnant also pointed out an interesting fact about performance, you can check this link if you are interested. He addresses performance concerns and shows that std::lock can be implemented efficiently, I can also recommend to read all the comments in that post.