Created
September 4, 2022 14:21
-
-
Save Nathaniel100/8e668b707ecd56d08db021cace922165 to your computer and use it in GitHub Desktop.
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
#include "hierarchical_mutex.h" | |
thread_local unsigned long HierarchicalMutex::this_thread_hierarchical_value = ULONG_MAX; |
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
#include <limits.h> | |
#include <stdint.h> | |
#include <mutex> | |
#include <thread> | |
class HierarchicalMutex { | |
public: | |
explicit HierarchicalMutex(unsigned long value) | |
: hierarchical_value(value), previous_hierarchical_value(0) {} | |
void lock() { | |
CheckViolation(); | |
mtx_.lock(); | |
UpdateValue(); | |
} | |
bool try_lock() { | |
CheckViolation(); | |
if (!mtx_.try_lock()) { | |
return false; | |
} | |
UpdateValue(); | |
return true; | |
} | |
void unlock() { | |
this_thread_hierarchical_value = previous_hierarchical_value; | |
mtx_.unlock(); | |
} | |
private: | |
void CheckViolation() { | |
if (this_thread_hierarchical_value <= hierarchical_value) { | |
throw std::logic_error("Hierarchical value vialates"); | |
} | |
} | |
void UpdateValue() { | |
this_thread_hierarchical_value = hierarchical_value; | |
previous_hierarchical_value = this_thread_hierarchical_value; | |
} | |
private: | |
std::mutex mtx_; | |
const unsigned long hierarchical_value; | |
unsigned long previous_hierarchical_value; | |
static thread_local unsigned long this_thread_hierarchical_value; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment