Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 

Am I safe enough if I use only the first method ?

NOTE: My question mostly refers to very small programs where at the most what I'll do is connect several clients to a server and resolve their inquiries with worker threads.

like image 501
Kalec Avatar asked Jan 14 '13 14:01

Kalec


People also ask

What is pthread_mutex_init?

The pthread_mutex_init() function initializes a mutex with the specified attributes for use. The new mutex may be used immediately for serializing critical resources. If attr is specified as NULL, all attributes are set to the default mutex attributes for the newly created mutex.

What type is pthread_mutex_t?

In AIX, the pthread_mutex_t data type is a structure; on other systems, it might be a pointer or another data type. A mutex must be created once. However, avoid calling the pthread_mutex_init subroutine more than once with the same mutex parameter (for example, in two threads concurrently executing the same code).

Can Pthread_mutex_unlock block?

Yes, it is a blocking call and will block until it gets the lock.

What is Pthread_mutex_recursive?

PTHREAD_MUTEX_RECURSIVE: Recursive type. This mutex type allows the same thread to lock the mutex multiple times before it is unlocked. Recursive mutex maintains the count of locks that will not be released if the number of unlocks and the number of locks are different, and no other thread can lock this mutex.


1 Answers

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.

like image 165
Jens Gustedt Avatar answered Sep 19 '22 23:09

Jens Gustedt