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.
Code from Michael Foukarakis is almost good but he initializes mutex twice which leads to undefined behavior. It should be just like that:
I acutally uses this code in production, and I know it works correctly on Linux, Solaris, HP-UX, AIX, Mac OSX and FreeBSD.
/edit
You also need to add proper linker flag to compile this.
AIX, Linux, FreeBSD:
CPLATFORM += -pthread
mingw32:
LDFLAGS += -lpthread
On Linux (but this is non portable to other systems), if the mutex is a global or static variable, you could initialize it like
(and by the way, the example is from
pthread_mutex_init(3)
man pages!)You need to add mutex attributes when creating the mutex.
Call
pthread_mutexattr_init
, thenpthread_mutexattr_settype
withPTHREAD_MUTEX_RECURSIVE
then use these attributes withpthread_mutex_init
. Readman pthread_mutexattr_init
for more info.To create a recursive mutex, use:
where type is
PTHREAD_MUTEX_RECURSIVE
.Don't forget to check the return value!
Example:
or alternatively, initialize at runtime (don't do both, it's undefined behaviour):