Skip to content

Instantly share code, notes, and snippets.

@picanumber
Last active August 9, 2021 15:58
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 picanumber/b35f555c6769d442e9252c792402e9be to your computer and use it in GitHub Desktop.
Save picanumber/b35f555c6769d442e9252c792402e9be to your computer and use it in GitHub Desktop.
template <class T> class Locking
{
T _data;
mutable std::recursive_mutex _mtx;
template <class U> class CallProxy
{
U *_p;
std::recursive_mutex &_mtx;
mutable bool _own;
public:
CallProxy(U *pp, std::recursive_mutex &mtx) : _p(pp), _mtx(mtx), _own(true)
{
}
CallProxy(CallProxy const &other)
: _p(other._p), _mtx(other._mtx), _own(true)
{
other._own = false;
}
~CallProxy()
{
if (_own)
{
_mtx.unlock();
}
}
CallProxy &operator=(CallProxy const &) = delete;
U *operator->()
{
return _p;
}
};
public:
template <class U> Locking(U &&data) : _data(std::forward<U>(data))
{
}
CallProxy<T> operator->()
{
_mtx.lock();
return CallProxy<T>(&_data, _mtx);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment