std::unique_lock, std::shared_lock and std::lock_guard in cpp
std::unique_lock and std::lock_guard
std::unique_lock and std::lock_guard are same by default.
std::unique_lock is more versatile than std::lock_guard. It could be used on multiple mutex occupation.
std::unique_lock<std::mutex> lk1(mutex1, std::defer_lock);
std::unique_lock<std::mutex> lk2(mutex2, std::defer_lock);
std::lock(lk1, lk2);
std::shared_lock
multiple std::shared_lock instance could hold the mutex simultaneously. For example multiple users are reading the information, each read hold the mutex with std::shared_mutex.
If one or more readers hold the mutex with std::shared_mutex, the writer could not hold the mutex with std::unique_lock. So that the information could not be modified while someone are reading it.
ref
c++ - std::unique_lockstd::mutex or std::lock_guardstd::mutex? - Stack Overflow: https://stackoverflow.com/questions/20516773/stdunique-lockstdmutex-or-stdlock-guardstdmutex
c++ - What's the best way to lock multiple std::mutex'es? - Stack Overflow: https://stackoverflow.com/questions/17113619/whats-the-best-way-to-lock-multiple-stdmutexes/17113678#17113678
Understanding std::unique_lock and std::shared_lock in C++ - DEV Community: https://dev.to/vivekyadav200988/understanding-stduniquelock-and-stdsharedlock-in-c-73p
Understanding Locking Mechanisms in C++: std::lock_guard, std::unique_lock, and std::shared_lock | by Elysium Celeste | Medium: https://medium.com/@elysiumceleste/understanding-locking-mechanisms-in-c-std-lock-guard-std-unique-lock-and-std-shared-lock-a8aac4d575ce
浙公网安备 33010602011771号