Skip to content

Instantly share code, notes, and snippets.

@nguditi
Created April 12, 2023 03:17
Show Gist options
  • Save nguditi/de861382519660aa925ec8bcaa05faa3 to your computer and use it in GitHub Desktop.
Save nguditi/de861382519660aa925ec8bcaa05faa3 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <thread>
#include <mutex>
class RecursiveMutex {
public:
void lock() {
std::unique_lock<std::mutex> lock(m_mutex);
if (m_owner == std::this_thread::get_id()) {
// This thread already owns the lock, so increment the recursion count
m_recursion_count++;
return;
}
// This thread does not yet own the lock, so wait until it can acquire it
m_cv.wait(lock, [this](){ return m_owner == std::thread::id{}; });
m_owner = std::this_thread::get_id();
m_recursion_count = 1;
}
void unlock() {
std::unique_lock<std::mutex> lock(m_mutex);
if (m_owner != std::this_thread::get_id()) {
throw std::runtime_error("Thread does not own the lock");
}
m_recursion_count--;
if (m_recursion_count == 0) {
m_owner = std::thread::id{};
m_cv.notify_one();
}
}
private:
std::mutex m_mutex;
std::condition_variable m_cv;
std::thread::id m_owner{};
int m_recursion_count = 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment