2
#include <pthread.h>

pthread_mutex_t* mut;

int main()
{
        mut = PTHREAD_MUTEX_INITIALIZER;
}

The above code spits out error: expected expression before ‘{’ token.

#include <pthread.h>

pthread_mutex_t* mut = PTHREAD_MUTEX_INITIALIZER;

int main()
{

}

The above code spits out warning: braces around scalar initializer

So how am I supposed to initialize a mutex?

2 Answers2

6

It is a type error, you should use: pthread_mutex_t instead of pthread_mutex_t*:

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

The reason why compiler complains is that is tries to assign this macro expansion of PTHREAD_MUTEX_INITIALIZER to a pointer:

{ { 0, 0, 0, 0, 0, __PTHREAD_SPINS, { 0, 0 } } }

With the corrected approach, you may pass &mut everywhere you need pthread_mutex_t*.

syntagma
  • 23,346
  • 16
  • 78
  • 134
1

Firstly you should declare it as pthread_mutex_t and not as a pointer pthread_mutex_t *. You should also decide if the mutex is global or local to a function.

If it's global you can initialize it using: pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

If it's local you have to call : pthread_mutex_init(&mut,NULL); (you have to check returned value)

Note that PTHREAD_MUTEX_INITIALIZER is a macro and you can't assign it to a pointer.

From pthread_mutex_init() man page :

Only mutex itself may be used for performing synchronization. The result of referring to copies of mutex in calls to pthread_mutex_lock(), pthread_mutex_trylock(), pthread_mutex_unlock(), and pthread_mutex_destroy() is undefined. Attempting to initialize an already initialized mutex results in undefined behavior.

Usually the method with the function call is used if you want to set attributes to the lock (second argument of the function) such as shareable between processes or recursive.

simo-r
  • 733
  • 1
  • 9
  • 13