Why doesn't the std :: mutex constructor in C ++ throw?

The function pthread_mutex_init()returns a nonzero value when the mutex cannot be initialized, and the class std::mutexin C ++ 11 has a constructor noexcept.

Suppose you decide to implement the mutex C ++ class on top of mutex pthreads. It completes the mutex pthread inside the class and tries to initialize it by calling pthread_mutex_init () in the constructor. If the function call returns a non-zero value, that is, an error, the error cannot be reported immediately, since the constructor cannot throw. One option is to throw an exception until the lock method is actually called by the mutex. But this approach seems wrong.

Is there any other way to do this using some clever tricks to ensure that initializing the mutex will always be successful?

Update: I am going to answer my question on this. According to the locale , in 30.4.1.3 pge 1163 it says: "If the initialization of an object of type mutex fails, an exception of type system_error will be thrown."

And the noexcept function can call functions inside the body, but only the caller cannot catch the exception. If an exception is thrown inside the noexcept function, std :: terminate will be called.

+4
source share
3 answers

std::mutex constexpr ( std::mutex ), pthread_mutex_init ( ) .

PTHREAD_MUTEX_INITIALIZER (, SRWLOCK_INIT Windows) .

+2

, , pthread_mutex_init std::mutex. / . !

+1

, pthread_mutex_init libstd++:

https://github.com/psp2sdk/libs/blob/master/include/c%2B%2B/bits/gthr-posix.h#L732

__gthread_mutex_init_function __gthread_mutex_init_function,

https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/std_mutex.h#L75

which is in the constructor std::mutexthrough its base class.


UPDATE

You can initialize the Pthread mutez with PTHREAD_MUTEX_INITIALIZER, and then

error checks are not performed

I think error handling may be delayed to lock functions; quote from section documentation pthread_mutex_lockand pthread_mutex_trylockERRORS:

EINVAL The value specified by mutex does not apply to the mutex initialized object.

This means that errors in pthread_mutex_initcan be safely ignored in the constructor std::mutex.

+1
source

Source: https://habr.com/ru/post/1693389/


All Articles