I notice that, in libraries like libpthread, there will be structures which can be allocated in one of two ways. For example, a pthread_mutex_t can be initialized statically via
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
or dynamically via
pthread_mutex_init(&lock);
However, unless I’m missing something, the pthread_mutex_init function is superfluous. That is, couldn’t I just do
lock = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
?
>Solution :
The declaration for pthread_mutex_init() is:
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
So you can provide selected attributes to the initializer via the function call which you cannot via an assignment using PTHREAD_MUTEX_INITIALIZER.
However, if you’re happy with the default attributes, there’s no obvious reason why you couldn’t use the ‘compound literal’ assignment notation.
Note that it would be unwise to ‘destroy’ a previously used mutex by an assignment reinitializing. Always use the pthread_mutex_destroy() function to destroy a mutex.