Types of Locks: std::lock_guard
This lesson gives an introduction to locks and explains how std::lock_guard is used in C++.
We'll cover the following...
Locks take care of their resources 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.
Locks are available in three different flavors: std::lock_guard
for the simple use-cases; std::unique-lock
for the advanced use-cases; std::shared_lock
is available (with C++14) and can be used to implement reader-writer locks.
First, the simple use-case:
Press + to interact
std::mutex m;m.lock();sharedVariable = getVar();m.unlock();
The mutex m
ensures that access to the critical section ...