Main Content

MISRA C:2012 Rule 22.13

Thread objects, thread synchronization objects and thread-specific storage pointers shall have appropriate storage duration

Since R2025a

Description

Rule Definition

Thread objects, thread synchronization objects and thread-specific storage pointers shall have appropriate storage duration.1

Rationale

Objects of type thrd_t, myx_t, cnd_t, and tss_t are shared between threads and used for controlling concurrent execution. These objects can be accessed during the entire lifetime of the application. If these objects have automatic or thread storage duration, they can be accessed outside of their lifetime, which results in undefined behavior.

To avoid undefined behavior, best practice is to use static storage duration for these objects.

Polyspace Implementation

Polyspace® reports a violation of this rule if objects of these types have automatic or thread storage duration:

  • thrd_t

  • mtx_t

  • cnd_t

  • tss_t

If your code uses objects of these types with inappropriate storage duration as function parameters, Polyspace reports violations. Violations are not reported if pointers to these objects are used as function parameters

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 function func() uses mtx_t and thrd_t objects of automatic storage duration. Polyspace reports violations on these objects.

#include <stdio.h>
#include <threads.h>
void foo(void);
void func() {
    mtx_t mutex;  //Noncompliant
    if (mtx_init(&mutex, mtx_plain) != thrd_success) {
        fprintf(stderr, "Failed to initialize mutex\n");
        return;
    }

    thrd_t thread; //Noncompliant
    // Create a thread that will use the mutex
    if (thrd_create(&thread,foo, NULL) != thrd_success) {
        fprintf(stderr, "Failed to create thread\n");
        mtx_destroy(&mutex);
        return;
    }

    // Immediately destroy the mutex
    mtx_destroy(&mutex);

    // Attempt to join the thread 
    thrd_join(thread, NULL);
}

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.