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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With