Does “pthread_mutex_t mutex = {0}” initialize mute

2019-07-24 02:23发布

问题:

Is it possible to initialize mutex in this way:

pthread_mutex_t  mutex = {0};

What is the difference between the following 3 initialization of mutex:

1) pthread_mutex_init(&mutex, NULL);
2) pthread_mutex_t  mutex = {0};
3) pthread_mutex_t  mutex = PTHREAD_MUTEX_INITIALIZER;

回答1:

  • With the first option, you control the time at which the mutex is initialized (also: the argument should be &mutex) by calling the initializer function explicitly.
  • The second option is assuming things about the internal layout of the pthread_mutex_t object, which is supposed to be opaque. It should not be used.
  • The third option initializes the mutex statically. If defined at global or static scope, it will be initialized at program startup. It can be used also at local scope, but this is not recommended, as it does not check for error conditions.

See also: http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_mutex_init.html