views:

21

answers:

2

When a thread has acquired the lock and execute the following code, Could the thread will unlock the lock it has acquired just with the return statement? some code like this.

static pthread_mutex_t mutex;

    int foo()
    {
        pthread_mutex_lock(mutex);

        .........
        execute some code here and some errors happen
                return -1;// but without pthread_mutex_unlock

        pthread_mutex_unlock(mutext)
        return 0;
    }

Some errors happens before pthread_mutex_unlock statement and the thread returns to the callee. Will the thread give back the mutext lock for other threads without executing pthread_mutex_unlock?

+1  A: 

No, it will not automatically unlock the mutex. You must explicitly call pthread_mutex_unlock() in the error path, if the mutex has been locked by the function.

caf
+2  A: 

No, the lock is not automatically released. This is why, in C++ code, it is common to use Resource Aquisition is Initialization (RAII), which takes advantage of construction/destruction to ensure that each call to the lock function has a corresponding call to unlock. If you are writing pure C code, though, you will need to make sure that you unlock the mutex, even in error situations, before returning.

Note that you can make your coding a little bit easier by doing the following:

  static inline int some_function_critical_section_unsynchronized(void) {
       // ...
  }
  int some_function(void) {
       int status = 0;
       pthread_mutex_lock(mutex);
       status = some_function_critical_section_unsynchronized();
       pthread_mutex_unlock(mutex);
       return status;
  }

In other words, if you can separate the logic into smaller functions, you may be able to tease out the locking code from your logic. Of course, sometimes this is not possible (like when coding in this fashion would make the critical section too large, and for performance, the less readable form is required).

If you can use C++, I would strongly suggest using boost::thread and boost::scoped_lock to ensure that the acquired mutex is automatically freed when its usage has gone out of scope.

Michael Aaron Safyan