Mutex locked or unlocked manually instead of through a scoped guard
ID |
c.maintainability.manual_mutex_lock |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Concurrency |
Language |
C / C++ |
Description
This calls lock(), unlock(), or try_lock() directly on a mutex. Without an RAII guard, an exception or an early return between the lock and its matching unlock leaves the mutex held forever, and every additional exit path in the function is another place that call can be forgotten. Wrap the mutex in std::lock_guard, std::unique_lock, or std::scoped_lock so the unlock happens automatically when the guard goes out of scope.
Rationale
This calls lock(), unlock(), or try_lock() directly on a mutex. Without an RAII guard, an exception or an early return between the lock and its matching unlock leaves the mutex held forever, and every additional exit path in the function is another place that call can be forgotten. Wrap the mutex in std::lock_guard, std::unique_lock, or std::scoped_lock so the unlock happens automatically when the guard goes out of scope.
The following code illustrates the pattern detected by this rule:
std::mutex m;
void manual_lock_unlock()
{
// FLAGGED: Mutex locked or unlocked manually instead of through a scoped guard
m.lock();
// FLAGGED: Mutex locked or unlocked manually instead of through a scoped guard
m.unlock();
}