Lock a mutex multiple times in the same thread

Megacan picture Megacan · May 12, 2010 · Viewed 33.9k times · Source

I'm developing an application on an embedded linux OS (uClinux) and I need to be able to lock the mutex more than once (by the same thread).

I have a mutex and a mutexattr defined and initialized as follows:

pthread_mutexattr_t waiting_barcode_mutexattr;
pthread_mutex_t waiting_barcode_mutex;

pthread_mutexattr_init(&waiting_barcode_mutexattr);
pthread_mutexattr_settype(&waiting_barcode_mutexattr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&waiting_barcode_mutex, &waiting_barcode_mutexattr);

But when I try to acquire the lock twice it blocks on the second lock:

pthread_mutex_lock(&waiting_barcode_mutex);
pthread_mutex_lock(&waiting_barcode_mutex);

Am I initializing it wrong or is there a better way of accomplishing the same?

Thanks in advance.

Conclusions:

  • Apparently PTHREAD_MUTEX_RECURSIVE or PTHREAD_MUTEX_RECURSIVE_NP don't work so I can't create a reentrant mutex.
  • try_lock is no good either. It acquires the lock if it can and returns an error if it can't acquire the lock. Unfortunately the error just informs me that the mutex is already in use and I can´t find out if the current thread already owns the lock or not.
  • pthread_mutex_lock can return an error if the current thread has the lock but for that I need to create a mutex of the type PTHREAD_MUTEX_ERRORCHECK, and I can't create one either.

Answer

Jeff B picture Jeff B · May 12, 2010

Isn't this doing what you would expect?

The first call acquires the lock, and the second one will block until the first lock is released (pthread_mutex_unlock). This is what locks do.

From the documentation:

"If the mutex is already locked, the calling thread blocks until the mutex becomes available."

Perhaps you want pthread_mutex_trylock? It's hard to say unless we know what you are trying to accomplish.

CORRECTION:

I didn't see that you were setting PTHREAD_MUTEX_RECURSIVE.... Let me think about this some more.

AFTER THINKING:

From poking around google codesearch, it looks like PTHREAD_MUTEX_RECURSIVE is not implemented in all libs. You may try PTHREAD_MUTEX_RECURSIVE_NP, or you may have do something fancy to get around this.