Skip to content

Instantly share code, notes, and snippets.

@SmallJoker
Last active December 29, 2023 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SmallJoker/f75cc0e029e1ee989d59e88eab1138cc to your computer and use it in GitHub Desktop.
Save SmallJoker/f75cc0e029e1ee989d59e88eab1138cc to your computer and use it in GitHub Desktop.
C++ RAII mutex locking, bound to userdata
// Auto-unlock wrapper for larger operations
/*
Exmaple usage:
struct MyStruct {
PtrLock<decltype(m_value)> getValues()
{
return PtrLock<decltype(m_value)>(m_lock, &m_value);
}
private:
std::mutex m_lock;
std::vector<int> m_value;
};
static void mycaller()
{
MyStruct s;
auto values = s.getValues();
values->push_back(42);
}
*/
template<typename T>
class PtrLock {
public:
PtrLock(std::mutex &m, T *ptr) :
m_mutex(m), m_ptr(ptr)
{
if (ptr)
m.lock();
}
~PtrLock()
{
if (m_ptr)
m_mutex.unlock();
}
DISABLE_COPY(PtrLock)
void release()
{
if (m_ptr)
m_mutex.unlock();
m_ptr = nullptr;
}
inline T *ptr() const { return m_ptr; }
// Synthetic sugar
inline T *operator->() const { return m_ptr; }
// Validation check
inline bool operator!() const { return !m_ptr; }
private:
std::mutex &m_mutex;
T *m_ptr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment