Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can you have multiple mutex locks?

If you have more than one mutex, each mutex is independent: a thread can hold neither, one or both of them. In your Reader , a thread first acquires mutex .

What is the difference between unique_lock and Lock_guard?

A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.

Does unique_lock automatically unlock?

The std::scoped_lock and std::unique_lock objects automate some aspects of locking, because they are capable of automatically unlocking.


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.