Skip to content

Instantly share code, notes, and snippets.

@Nathaniel100
Created September 4, 2022 14:21
Show Gist options
  • Save Nathaniel100/8e668b707ecd56d08db021cace922165 to your computer and use it in GitHub Desktop.
Save Nathaniel100/8e668b707ecd56d08db021cace922165 to your computer and use it in GitHub Desktop.
#include "hierarchical_mutex.h"
thread_local unsigned long HierarchicalMutex::this_thread_hierarchical_value = ULONG_MAX;
#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