Mutexes are often used for critical resources to prevent multiple threads accessing them at the same time. Sometimes, when locking mutexes, deadlock will happen when multiple threads hold each other's lock and the program come to a halt.
To prevent deadlock, one can try
Introduction
Whenever threads come into play, there are bounded to be shared memory or resources that each thread wants to access. But because of the random nature of execution of each thread, there will be corruption of data when multiple threads try to read and write into the same memory space. One possible way to fix the problem is using locking mechanism like a mutex. POSIX provides a mutex called pthread_mutex_t just for this purpose. See POS00-C Avoid race conditions with multiple threads for more information.
Deadlock can happen when multiple threads each holds a lock the other needs and are waiting for each other to release that resource. One way to fix the problem is to avoid circular wait by locking the mutex mutexes in a predefined order.
Noncompliant Code Example
Based on runtime environment and the scheduler on the operating system, the following code will have different behaviors. Let's assume function thread1 and thread2 are called consecutively as in pthread_create is called for thread2 right after pthread_create is called for thread1. If lucky, the code will run without any problems. In other timesHowever, with proper timing, the code will deadlock in which thread1 try thr1 tries to lock m1 while thread2 try ba2's mutex while thr2 tries to lock on m2 ba1's mutex and the program will not progress.
...
The solution to the deadlock problem is to lock in predefined order. In the following example, each thread will lock m1 first then m2based on bank_account's id in increasing order. This way circular wait problem is avoided and when one thread requires a lock will guarantee it will require the next lock.
...
Recommendation | Severity | Likelihood | Remediation Cost | Level | Priority |
---|---|---|---|---|---|
POS43-C | low | probable | medium | L3 | P4 P3 |
References
Wiki Markup |
---|
\[[pthread_mutex | https://computing.llnl.gov/tutorials/pthreads/#Mutexes]\] pthread_mutex tutorial \[[MITRE CWE:764 | http://cwe.mitre.org/data/definitions/764.html]\] Multiple Locks of Critical Resources \[[Bryant 03|AA. References#Bryant 03]\] Chapter 13, Concurrent Programming |
...