std::lock
(C++)
Locks the given Lockable objects lock1
, lock2
, …, lockn
using a deadlock avoidance algorithm to avoid Deadlock.
Though generally, when we refer to locks in C++, we dont use the “naked” std::lock
. The locks below employ RAII, which automatically lock and unlock a mutex. These are:
std::lock_guard
std::unique_lock
- NEW
std::scoped_lock
Resources
- https://en.cppreference.com/w/cpp/thread/lock
- https://en.cppreference.com/w/cpp/thread/unique_lock
- https://www.modernescpp.com/index.php/prefer-locks-to-mutexes/
Mutex vs. Lock
Always prefer locks to mutexes, using a
1ock_guard
Motivation is here: https://www.modernescpp.com/index.php/prefer-locks-to-mutexes/
Locks take care of their resource following the RAII idiom. A lock automatically binds its mutex in the constructor and releases it in the destructor. This considerably reduces the risk of a deadlock because the runtime takes care of the mutex.
BAD
- Easy to forget to unlock, easy to result in Deadlock
GOOD
- Mutex gets released at the end of critical section (destructor gets called)
- he lifetime of std::lock_guard is limited by the brackets (http://en.cppreference.com/w/cpp/language/scope#Block_scope). That means its lifetime ends when it leaves the critical section.
Types of locks
std::lock_guard
https://cplusplus.com/reference/mutex/lock_guard/
The class lock_guard
is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block.
unique_lock
std::unique_lock
is mightier but more expansive than its small brother std::lock_guard.
unique_lock
locks in exclusive mode.
- https://en.cppreference.com/w/cpp/thread/unique_lock
- https://stackoverflow.com/questions/14709233/how-to-use-create-unique-lock-in-c
shared_lock
shared_lock
allows deferred locking, timed locking and transfer of lock ownership.
https://en.cppreference.com/w/cpp/thread/shared_lock/shared_lock