Main Content

MISRA C:2012 Rule 22.18

Non-recursive mutexes shall not be recursively locked

Since R2025a

Description

Rule Definition

Non-recursive mutexes shall not be recursively locked.1

Rationale

Recursive mutexes are usually locked by recursively called functions. Recursive mutexes can be locked multiple times without causing a deadlock as long as it is unlocked the same number of times.

Locking a nonrecursive mutex multiple times without unlocking it first is undefined behavior. Similarly, unlocking a nonrecursive mutex multiple times without locking it first is undefined behavior.

Polyspace Implementation

Polyspace® report a violation of this rule when:

  • A thread locks a nonrecursive mutex.

  • The thread locks the mutex again without unlocking it first.

Recursive mutexes are initialized by using the constant mtx_recursive in the function mtx_init(). Polyspace recognizes recursive_mutex as a recursive mutex:

mtx_t recursive_mutex;

void foo(){
    mtx_init( &recursive_mutex, mtx_recursive); // Recursive mutex
    
}

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, the mutex object plain_mutex is nonrecursive. Locking this mutex multiple times without unlocking it first is undefined behavior. Polyspace reports a violation. Locking the recursive mutex recusrsive_mutex multiple times is not a violation.

#include<threads.h>

mtx_t recursive_mutex;
mtx_t plain_mutex;

void foo(){
    mtx_lock(&recursive_mutex);
    mtx_lock(&recursive_mutex);
    mtx_lock(&recursive_mutex);
    mtx_unlock(&recursive_mutex);
    mtx_unlock(&recursive_mutex);
    mtx_unlock(&recursive_mutex);  //Compliant
    mtx_lock(&plain_mutex);
    mtx_lock(&plain_mutex);  //Noncompliant
    
}

thrd_t id1;

int main(){
    mtx_init( &recursive_mutex, mtx_recursive); // Recursive mutex
    mtx_init( &plain_mutex, mtx_plain); // Plain mutex
    thrd_create(&id1, foo, 0);
    //...
}

Check Information

Group: Resources
Category: Required
AGC Category: Required

Version History

Introduced in R2025a


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.