Mutexes that are used to protect accesses to shared data may be locked using the lock()
member function, and unlocked using the unlock()
member function. If an exception occurs between the call to lock()
and the call to unlock()
, and the exception changes control flow such that unlock()
is not called, the mutex will be left in the locked state and no critical sections protected by that mutex will be allowed to execute. This is likely to lead to deadlock.
C++ supplies a lock classes, lock_guard
class , unique_lock
, and shared_lock
, that can be initialized with a mutex. In its constructor, a lock_guard
object lock object locks the mutex, and in its destructor, it unlocks the mutex. If an exception occurs and takes control flow out of the scope of the lock_guard object, its destructor will unlock the mutex and the program can continue working normally.
Mutexes should always be locked with a lock_guard
object lock object to protect against unanticipated control flow caused by exceptions.
Noncompliant Code Example
This noncompliant code example manipulates shared data and protects the critical section by locking the mutex. When it is finished, it unlocks the mutex. However, if an exception occurs while manipulating the shared data, the mutex will remain locked.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <mutex> void manipulate_shared_data(std::mutex &pm) { pm.lock(); // Perform work on shared data. pm.unlock(); } |
Compliant Solution
This compliant solution uses a lock_guard
object to ensure that the mutex will be unlocked even if an exception occurs.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <mutex> void manipulate_shared_data(std::mutex &pm) { std::lock_guard<std::mutex> guardlk(pm); // Perform work on shared data. } |
Risk Assessment
If an exception occurs while a mutex is locked, deadlock may result.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON51-CPP | Low | Probable | Low | P6 | L2 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
| |||
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Bibliography
[ISO/IEC 14882-2014] | [thread.lock] "Locks" |
...