Question

As a rule, I was told that any system call (or alike) should be tested for errors on return.

When initializing a pthread mutex using:

pthread_mutex_t myMutex = PTHREAD_MUTEX_INITIALIZER; 

We don't check wether the operation was successful or not.

But using this macro instead of dynamic initialization seems to be a common practice.

Is there any good reason an error check isn't needed in this case?

Était-ce utile?

La solution

The reason error checking isn't necessary is because static initialization cannot fail. In the most common implementations, PTHREAD_MUTEX_INITIALIZER will be something along the lines of 0 or {} (depending on how pthread_mutex_t is defined), to ensure zero initialization, and the the various system calls which use the pthread_mutex_t are designed to treat a zero initialized pthread_mutex_t as if it had been initialized to all default values, either because the type was designed explicitly this way, or because the routines use lazy initialization.

(Note that PTHREAD_MUTEX_INITIALIZER cannot be anything along the lines of __special_mutex_initializer(), since it can be used to initialize file scope static variables in C, and C requires compile time constant expressions for the initialization of static variables.)

EDIT:

For more information, you might want to read the rationale section of http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_init.html. This describes several different possible implementations, and some of the trade-offs involved.

Autres conseils

From IBM

Note: Mutex initialization using the PTHREAD_MUTEX_INITIALIZER does not immediately initialize the mutex. Instead, on first use, the pthread_mutex_lock() or pthread_mutex_trylock() functions branch into a slow path and cause the initialization of the mutex. Because a mutex is not just a simple memory object and requires that some resources be allocated by the system, an attempt to call pthread_mutex_destroy() or pthread_mutex_unlock() on a mutex that was statically initialized using PTHREAD_MUTEX_INITIALER and was not yet locked causes an EINVAL error.

If you use PTHREAD_MUTEX_INITIALIZER, you do the error checking later.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top