MISRA.STDLIB.MUTEX.NO_LOCK.2023

Missing lock for mutex variable

MISRA C:2012 AMD4 Rule 22.17 (Required): No thread shall unlock a mutex or call cnd_wait() or cnd_timedwait() for a mutex it has not locked before.

Category: Required

Analysis: Undecidable, System

Applies to: C11

Amplification

A mutex shall only be unlocked by a thread if it has been locked by that thread before.

The cnd_wait() and cnd_timedwait() functions shall only be called by a thread on a mutex that is locked by that thread.

Rationale

Unlocking a mutex which has not been locked by the calling thread is undefined behaviour. Calling cnd_wait() or cnd_timedwait() with mutex argument mtx requires that the mutex pointed to by mtx be locked by the calling thread.

Example

Copy
#include <threads.h>
mtx_t mutex;
int thread_func(void *arg)
{
    if (arg) {
        return 0;
    }
    mtx_unlock(&mutex);
    return 0;
}
int main()
{
    thrd_t tid;
    thrd_create(&tid, thread_func, NULL); //defect MISRA.STDLIB.MUTEX.NO_LOCK.2023
    thrd_join(tid, NULL);
    return 0;
}

See also

Dir 4.13, Rule 22.1, Rule 22.18

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