MISRA C:2012 Dir 5.2
Description
This checker is deactivated in a default Polyspace® as You Code analysis. See Checkers Deactivated in Polyspace as You Code Analysis (Polyspace Access).
Directive Definition
There shall be no deadlocks between threads.
This directive comes from MISRA C™: 2012 Amendment 4.
Rationale
A deadlock can occur when the threads sharing synchronization resources create a circular chain, with each thread waiting for another thread. Consider this code:
mtx_t mtx1, mtx2; void worker1() { /*In thread T1*/ mtx_lock(&mtx1); //... mtx_lock(&mtx2); // potential deadlock } void worker2() { /*In thread T2*/ mtx_lock(&mtx2); //... mtx_lock(&mtx1); // potential deadlock }
worker1()
and
worker2()
run concurrently in two threads. The function
worker1()
locks mtx1
and then tries to lock
mtx2
, while worker2()
locks
mtx2
and then tries to lock mtx1
. If both
threads lock their first mutex before either tries to lock their second, then each
thread remains waiting for the other to release its mutex, leading to a deadlock.To avoid deadlocks, use mutexes in a fixed global noncyclic order.
Polyspace Implementation
Polyspace reports violations of this directive when multiple threads wait on their mutex objects cyclically:
Each thread waits for another thread to unlock a mutex.
The threads form a closed cycle.
Polyspace recognizes the threads and mutex objects from the C11 library. See Auto-Detection of Thread Creation and Critical Section in Polyspace.
You can also manually specify your threads by using the option Tasks (-entry-points)
, and your mutex objects by using Critical section details (-critical-section-begin
-critical-section-end)
.
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
Check Information
Group: Concurrency Considerations |
Category: Required |
AGC Category: Required |
Version History
Introduced in R2024b