Locks
In this lesson, we will learn about different locks and their usage in embedded programming.
We'll cover the following...
Locks are available in three different forms:
-
std::lock_guardfor simple use-cases -
std::unique-lockfor advanced use-cases -
std::shared_lockis available with C++14 and can be used to implement reader-writer locks.
Locks need the header
<mutex>.
RAII-Idiom (Resource Acquisition Is Initialization)
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 reduces the risk of a deadlock because the runtime handles the mutex.
If the lock goes out of scope, the resource will be immediately released.
std::lock_guard
First, the simple use-case:
Press + to interact
std::mutex m;m.lock();sharedVariable = getVar();m.unlock();
The mutex m ...
Ask