Why is this an issue?
Mutexes are synchronization primitives that allow to manage concurrency.
- non recursive mutexes are targeted by this rule. They can be locked/unlocked only once. Any locking/unlocking sequence that contains
two consecutive identical operations leads to an undefined behaviour.
- recursive mutexes are not target by this rule. They can be locked several times and unlocked several times as long as the number of
locks/unlocks is the same.
This rule raises an issue when a pthread_mutex_t
is locked or unlocked several times in a row. We assume that all
pthread_mutex_t
are non-recursive (this is the most common case).
Noncompliant code example
pthread_mutex_t mtx1;
void bad1(void)
{
pthread_mutex_lock(&mtx1);
pthread_mutex_lock(&mtx1);
}
void bad2(void)
{
pthread_mutex_unlock(&mtx1);
pthread_mutex_unlock(&mtx1);
}
Compliant solution
pthread_mutex_t mtx1;
void ok(void)
{
pthread_mutex_lock(&mtx1);
pthread_mutex_unlock(&mtx1);
}
Resources