0

According to POSIX, I can statically initialise a mutex this way:

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;

However, what if I want the mutex to be recursive? Mutexes are non-recursive be default and there's no way to supply mutex attributes to the static initialisation.

jotik
  • 17,044
  • 13
  • 58
  • 123
Martin Sustrik
  • 783
  • 10
  • 22
  • Is that C or C++? Suggestions might differ depending on which language you're using. – NPE Dec 07 '12 at 08:03

2 Answers2

0

Try :

pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; 
jotik
  • 17,044
  • 13
  • 58
  • 123
O.C.
  • 6,711
  • 1
  • 25
  • 26
  • _NP suffix means non portable. It works for linux. Try with PTHREAD_RECURSIVE_MUTEX_INITIALIZER as described here http://www.sourceware.org/pthreads-win32/manual/pthread_mutex_init.html if you care for portability – O.C. Dec 07 '12 at 09:35
  • PTHREAD_RECURSIVE_MUTEX_INITIALIZER is not defined by POSIX. What operating systems it is supported in? – Martin Sustrik Dec 07 '12 at 11:38
0

It seems there is no portable way to do this. A workaround may be initialise the mutex dynamically when it is first used. To prevent race conditions while doing the initialisation another non-recursive statically initialised mutex can be used.

Martin Sustrik
  • 783
  • 10
  • 22