# V2640. MISRA. Thread objects, thread synchronization objects and thread-specific storage pointers should have appropriate storage duration.

This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guidelines.

This diagnostic rule is relevant only for C.

Objects of the `cnd_t`, `mtx_t`, `thrd_t`, and `tss_t` types from the Concurrency support library should not have automatic or thread-local storage duration.

Synchronization objects are typically accessed from multiple threads. In such cases, when using automatic or thread-local storage duration, developers risk accessing an object whose lifetime has already ended. This can lead to undefined behavior and uncontrolled thread execution.

The diagnostic rule helps reduce the likelihood of errors and eliminate thread dependencies on the lifetime of synchronization objects.

The example of the incorrect code:

    int Task1(void *mtx)
    {
      mtx_lock((mtx_t*)mtx);   // can be dangling pointer
      // do stuff
      mtx_unlock((mtx_t*)mtx); // can be dangling pointer
      return 0;
    }

    void RunTask()
    {
      thrd_t thread1;
      mtx_t mtx;

      mtx_init(&mtx, mtx_plain);
      thrd_create(&thread1, Task1, &mtx);
    }

In this case, the lifetime of the `mtx` object may end before it is locked or unlocked in the child thread.

The fixed version of this code:

    thrd_t thread1;
    mtx_t mtx;

    int Task1(void *mtx)
    {
      mtx_lock((mtx_t*)mtx);
      // do stuff
      mtx_unlock((mtx_t*)mtx);
      return 0;
    }

    void RunTask()
    {
      mtx_init(&mtx, mtx_plain);
      thrd_create(&thread1, Task1, &mtx);
    }

This diagnostic is classified as:

MISRA-C-2023-22.13