Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: How do you declare a recursive mutex with POSIX threads?

I am a bit confused on how to declare a recursive mutex using pthread. What I try to do is have only one thread at a time be able to run a piece of code(including functions) but after scepticism I figured out that the use of mutexes would not work and that instead I should use recursive mutexes. Here is my code:

pthread_mutex_lock(&mutex);                   // LOCK  item = queue_peek(queue);                     // get last item in queue item_buff=item;                               // save item to a buffer queue_removelast(queue);                      // remove last item from queue  pthread_mutex_unlock(&mutex);                 // UNLOCK 

So what I try to do is just read/remove from the queue serially.

The thing is that there isn't any example out there on how to declare recursive mutexes. Or there maybe a few but they don't compile for me.

like image 732
Pithikos Avatar asked Aug 12 '11 08:08

Pithikos


People also ask

How do you make a recursive mutex?

To create a recursive mutex, use: #include <pthread. h> int pthread_mutexatttr_settype(pthread_mutexattr_t *attr, int type); where type is PTHREAD_MUTEX_RECURSIVE .

What is recursive mutex in C?

In computer science, the reentrant mutex (recursive mutex, recursive lock) is a particular type of mutual exclusion (mutex) device that may be locked multiple times by the same process/thread, without causing a deadlock.

What is Posix mutex?

It is an abbreviation for “mutual exclusion”. The functions of mutex are provide for creating, destroying, locking and unlocking mutexes. It is used to protect shared data from simultaneous access. It can be locked and unlocked. Once it is locked, current thread owns mutex until it is not unlocked.

Is mutex recursive?

E.g. in Java mutexes are always recursive (the same thread may twice "synchronize" on the same object).


1 Answers

The code from Michael Foukarakis is almost good but he initializes the mutex twice which leads to undefined behavior. It should just be:

pthread_mutex_t Mutex; pthread_mutexattr_t Attr;  pthread_mutexattr_init(&Attr); pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&Mutex, &Attr); 

I actually use this code in production, and I know it works correctly on Linux, Solaris, HP-UX, AIX, Mac OSX and FreeBSD.

You also need to add proper linker flag to compile this:

AIX, Linux, FreeBSD: CPLATFORM += -pthread  mingw32: LDFLAGS += -lpthread 
like image 146
Piotr Kukielka Avatar answered Sep 21 '22 16:09

Piotr Kukielka