While looking at the C++ Reference for std::mutex
, I noticed that the constructor for std::mutex
is marked constexpr
.
This is surprising at first, since we usually have to make a system call (either pthread_mutex_init()
(POSIX) or CreateMutex()
(Windows) to initialize a mutex. However, on closer inspection, for POSIX, one can use the constant PTHREAD_MUTEX_INITIALIZER
to statically initialize the mutex (perhaps as a global variable), though I can find no equivalent for Windows.
However, even if this static initialization for POSIX was the reason behind the constexpr
constructor, there're still various issues with an implementation:
- On Windows (and perhaps other non-POSIX systems), there may not be a way to statically initialize mutexes.
- It was impossible to have different code paths depending on whether the constructor is being called at compilation time until C++20's
std::is_constant_evaluated()
was added, so we don't have a way to determine ifPTHREAD_MUTEX_INITIALIZER
orpthread_mutex_init()
should be used.
So, how does one implement the constexpr
constructor for std::mutex
?
Aucun commentaire:
Enregistrer un commentaire