Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialization: Function vs. literal

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading