The pthread_mutex_init()
function returns a non-zero value when it fails to initialize the mutex, while the std::mutex
class in C++11 has a constructor of noexcept
.
Say one chooses to implement a C++ mutex class on top of pthreads mutex. He wraps a pthread mutex inside the class and tries to initialize it by calling pthread_mutex_init() in constructor. If the function call returns a value other than zero, meaning error, the error can't be reported immediately since the constructor can not throw. One alternative is to throw an exception until the lock method is actually called on the mutex. But this approach just seems wrong.
Is there another way to do this, employing some clever tricks to guarantee that initializing a mutex always succeed?
Update: I am going to answer my own question on this one. According to language standard, in 30.4.1.3 pge 1163, it says ". If initialization of an object of a mutex type fails, an exception of type system_error shall be thrown. "
And a function of noexcept can throw inside the function body, it is just the caller can not catch the exception. If an exception is thrown inside a noexcept function, std::terminate will be called.
std::mutex
must be implemented by using POSIX threads, i.e.,pthread
library. – Daniel Langr