Main Content

MISRA C:2023 Rule 21.26

The Standard Library function mtx_timedlock() shall only be invoked on mutex objects of appropriate mutex type

Since R2025b

Description

Rule Definition

The Standard Library function mtx_timedlock() shall only be invoked on mutex objects of appropriate mutex type.1

Rationale

The function mtx_timedlock() should only be used on mutexes that support a timeout functionality, specifically those initialized with the type mtx_timed or mtx_timed | mtx_recursive. Using mtx_timedlock() on a mutex initialized with other types, such as mtx_plain, results in undefined behavior.

For example, the following code results in undefined behavior:

mtx_t m;
mtx_init(&m, mtx_plain);
mtx_timedlock(&m, ts);

Polyspace Implementation

The rule checker reports a violation if a mutex of type mtx_t used by mtx_timedlock() was not previously initialized with type mtx_timed or mtx_timed | mtx_recursive.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, the mutexes R2 and R4 are not initialized to support a timeout and therefore violate the rule.

#include <stdint.h>
#include <time.h>
#include <threads.h>

mtx_t R1;
mtx_t R2;
mtx_t R3;
mtx_t R4;

void init_mutexes(void) {
    mtx_init(&R1, mtx_timed);                    
    mtx_init(&R2, mtx_plain);                    
    mtx_init(&R3, mtx_timed | mtx_recursive);    
    mtx_init(&R4, mtx_plain | mtx_recursive);    
}

void lock_mutexes(struct timespec* ts) {
    mtx_timedlock(&R1, ts); // Compliant: R1 was initialized with mtx_timed
    mtx_timedlock(&R2, ts); // Noncompliant R2 was not initialized with mtx_timed
    mtx_timedlock(&R3, ts); // Compliant: R3 was initialized with mtx_timed | mtx_recursive
    mtx_timedlock(&R4, ts); // Noncompliant: R4 was not initialized with mtx_timed
}

int main(void) {
    struct timespec ts;
    init_mutexes();
    lock_mutexes(&ts);
    return 0;
}

Check Information

Group: Standard libraries
Category: Required
AGC Category: Required

Version History

Introduced in R2025b


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.