Last active
December 29, 2023 18:52
-
-
Save SmallJoker/f75cc0e029e1ee989d59e88eab1138cc to your computer and use it in GitHub Desktop.
C++ RAII mutex locking, bound to userdata
This file contains 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
// 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