PTHREAD_MUTEX_INITIALIZER vs pthread_mutex_init ( &mutex, param)

By older versions of the POSIX standard the first method with an initializer is only guaranteed to work with statically allocated variables, not when the variable is an auto variable that is defined in a function body. Although I have never seen a platform where this would not be allowed, even for auto variables, and this restriction has been removed in the latest version of the POSIX standard.

The static variant is really preferable if you may, since it allows to write bootstrap code much easier. Whenever at run time you enter into code that uses such a mutex, you can be assured that the mutex is initialized. This is a precious information in multi-threading context.

The method using an init function is preferable when you need special properties for your mutex, such as being recursive e.g or being shareable between processes, not only between threads.

Leave a Comment