You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Pthread Mutual Exclusion (Mutex) locks are used to avoid simultaneous usage of common resources. There are several types of mutex locks defined by pthreads which include NORMAL, ERRORCHECK, RECURSIVE and DEFAULT.

POSIX defines PTHREAD_MUTEX_NORMAL locks to have the following undefined behavior [Open Group 4 ]

This type of mutex does not provide deadlock detection. A thread attempting to relock this mutex without first unlocking it shall deadlock. An error is not returned to the caller. Attempting to unlock a mutex locked by a different thread results in undefined behavior. Attempting to unlock an unlocked mutex results in undefined behavior.

The DEFAULT mutex type of pthreads is also generally mapped to PTHREAD_MUTEX_NORMAL which is seen across various implementations [SOL 10 ]. Usage of NORMAL locks should be avoided and ERRORCHECK or RECURSIVE locks should be explicitly defined when using mutex locks.

Noncompliant Code Example

The non compliant code example shows a simple mutex being created using PTHREAD_MUTEX_NORMAL. It should be noted that no return code is expected by the caller when NORMAL mutexes are used.

 pthread_mutexattr_t attr;
 pthread_mutex_t mutex;
 size_t const shared_var = 0;

 int main(){
     int rc =0;

     rc = pthread_mutexattr_settype(&mutex, PTHREAD_MUTEX_NORMAL);
     /*Check Return Code*/

     rc = pthread_mutex_init(&mutex, &attr);
     /*Check Return Code*/

     pthread_mutex_lock(&mutex);

     /* Critical Region*/

     pthread_mutex_unlock(&mutex);

     return 0;
 }

Compliant Solution

The compliant solution shows a pthread mutex lock being created with type PTHREAD_MUTEX_ERRORCHECK where return codes will be available during locking and unlocking.

 pthread_mutexattr_t attr;
 pthread_mutex_t mutex;
 size_t const shared_var = 0;

 int main(){
     int rc =0;

     rc = pthread_mutexattr_settype(&mutex, PTHREAD_MUTEX_ERRORCHECK);
     /*Check Return Code*/

     rc = pthread_mutex_init(&mutex, &attr);
     /*Check Return Code*/

     rc = pthread_mutex_lock(&mutex);
     /*Handle error if any*/
     /* Critical Region*/

     rc = pthread_mutex_unlock(&mutex);
     /*Handle error if any*/

     return 0;
 }

Risk Assessment

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

POSXX-C

high

likely

medium

P12

L1

References

[Open Group 4 ]
[SOL 10 ]

  • No labels