Created
May 31, 2017 23:56
-
-
Save BillyONeal/ae097ce5626b75de26798048b1d43cf6 to your computer and use it in GitHub Desktop.
Mutex Next
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CLASS mutex | |
class mutex | |
{ // class for mutual exclusion | |
public: | |
constexpr mutex() _NOEXCEPT | |
: _Data() | |
{ // construct std::mutex | |
} | |
mutex(const mutex&) = delete; | |
mutex& operator=(const mutex&) = delete; | |
#if _STD_MUTEX_LEVEL >= 1 | |
// Vista+ uses SRWLOCK, which provides trivial destruction and never fails | |
~mutex() _NOEXCEPT = default; | |
void lock() _NOEXCEPT // Strengthened | |
{ // lock the mutex | |
__std_mutex_lock_vista(&_Data._Data); | |
} | |
bool try_lock() _NOEXCEPT // Strengthened | |
{ // try to lock the mutex | |
return (__std_mutex_try_lock_vista(&_Data._Data) != 0); | |
} | |
void unlock() _NOEXCEPT // Strengthened | |
{ // unlock the mutex | |
__std_mutex_unlock_vista(&_Data._Data); | |
} | |
#else /* ^^^ _STD_MUTEX_LEVEL >= 1 ^^^ // vvv _STD_MUTEX_LEVEL == 0 vvv */ | |
// Windows XP mode tries SRWLOCK, falls back to separately allocated | |
// CRITICAL_SECTION (allocated on first lock() or try_lock() attempt) | |
~mutex() _NOEXCEPT | |
{ // destroy std::mutex | |
__std_mutex_destroy_xp(&_Data); | |
} | |
void lock() | |
{ // lock the mutex | |
if (__std_mutex_lock_xp(&_Data) != __std_win32_success) | |
{ // failed to allocate CRITICAL_SECTION | |
_THROW(system_error, _STD make_error_code(errc::resource_unavailable_try_again)); | |
} | |
} | |
bool try_lock() | |
{ // try to lock the mutex | |
bool _Result; | |
if (__std_mutex_try_lock_xp(&_Data, &_Result) != __std_win32_success) | |
{ // failed to allocate CRITICAL_SECTION | |
_THROW(system_error, _STD make_error_code(errc::resource_unavailable_try_again)); | |
} | |
return (_Result); | |
} | |
void unlock() _NOEXCEPT // Strengthened | |
{ // unlock the mutex | |
__std_mutex_unlock_xp(&_Data); | |
} | |
#endif /* _STD_MUTEX_LEVEL */ | |
private: | |
friend condition_variable; | |
friend _STDEXT condition_variable_light; | |
__std_mutex_data _Data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment