Scoped Locking

Learn about scoped locking.

We'll cover the following...

Locks (scoped 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.

There are two types of locks available in C++11, std::lock_guard for simple situations and std::unique-lock for the advanced use case.

std::lock_guard

First, let’s look at the simple use case.

Press + to interact
mutex m;
m.lock();
sharedVariable= getVar();
m.unlock();

With so little code, mutex m ensures access to the critical section sharedVariable= getVar() is sequential. Sequential means that, in this ...