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)
To create a recursive mutex, use:
#include
int pthread_mutexatttr_settype(pthread_mutexattr_t *attr,
int type);
where type is PTHREAD_MUTEX_RECURSIVE.
Don't forget to check the return value!
Example:
/* or PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP */
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutexattr_t mta;
or alternatively, initialize at runtime (don't do both, it's undefined behaviour):
pthread_mutexattr_init(&mta);
/* or PTHREAD_MUTEX_RECURSIVE_NP */
pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &mta);