Last active
August 9, 2021 15:58
-
-
Save picanumber/b35f555c6769d442e9252c792402e9be to your computer and use it in GitHub Desktop.
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
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