PTHREAD_MUTEX_INITIALIZER vs pthread_mutex_init (& mutex, param)

Is there any difference between

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 

Or

 pthread_mutex_t lock; pthread_mutex_init ( &lock, NULL); 

How confident am I if I use only the first method?

NOTE. . My question mainly relates to very small programs, where, at best, I have to connect several clients to the server and resolve their requests with workflows.

+52
c pthreads mutex ubuntu
Jan 14 '13 at 14:10
source share
3 answers

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

The static option is really preferable if you can, since it makes it easier to write bootstrap code. Whenever at runtime you enter code that uses such a mutex, you can be sure that the mutex is initialized. This is valuable information in a multi-threaded context.

A method using the init function is preferred when you need special properties for your mutex, such as recursive ones, for example, or sharing between processes, not just between threads.

+45
Jan 14 '13 at 14:44
source share

You can set additional mutex attributes using dynamic initialization, plus you can only use the dynamic method if you add a bunch of mutexes at runtime.

There is nothing wrong with a static approach if it suits your needs.

+5
Jan 14 '13 at 14:16
source share

In cases where mutex attributes are appropriate by default, the PTHREAD_MUTEX_INITIALIZER macro can be used to initialize mutexes.

If you want to specify attributes for mutex, go to dynamic initialization ........

The effect should be equivalent to dynamic initialization by calling pthread_mutex_init () with the attr parameter defined as NULL, except that no error checks are performed.

+2
Nov 29 '13 at 6:29
source share



All Articles