MISRA.STDLIB.MUTEX.DBL_LOCK.2023

Mutex variable is double locked

MISRA C 2012 AMD4 Rule 22.18 (Required): Non-recursive mutexes shall not be recursively locked.

Category: Required

Analysis: Undecidable, System

Applies to: C11

Amplification

A non-recursive mutex shall only be locked by a thread if it has not already been locked by that before.

Rationale

It is undefined behaviour if a non-recursive mutex is recursively locked by the calling thread. If the thread also attempts to unlock the mutex twice, the second call to mtx_unlock() will also result in undefined behaviour, since the mutex then will already be unlocked.

Example

Copy
mtx_t Ra;
mtx_t Rb;


int32_t t1( void *ignore ) /* Thread 1 */
{
 mtx_lock ( &Rb ); /* Compliant */
 mtx_lock ( &Rb ); /* Compliant - Rb is recursive */
 mtx_unlock( &Rb ); /* Rb still locked */
 mtx_unlock( &Rb ); /* Rb gets unlocked */

 mtx_lock ( &Ra ); /* Compliant */
 mtx_lock ( &Ra ); /* Non-compliant - undefined behaviour, deadlock possible */
 mtx_unlock( &Ra ); /* If reachable (i.e. no deadlock), Ra gets unlocked */
 mtx_unlock( &Ra ); /* Undefined behaviour if reachable */
 
 return 0;
}


thrd_t id1;
thrd_t id2;

int32_t main(void)
{
 mtx_init ( &Ra, mtx_plain );
 mtx_init ( &Rb, mtx_recursive );
 thrd_create( &id1, t1, NULL );
 ...
}

See also

Dir 4.13, Rule 22.1, Rule 22.17

"MISRA", "MISRA C" and "MISRA C++" are registered trademarks of The MISRA Consortium Limited. ​