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

C++MultithreadingC++11

C++ Problem Overview


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


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?

C++ Solutions


Solution 1 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2486888View Question on Stackoverflow
Solution 1 - C++Stephan DollbergView Answer on Stackoverflow