Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <mutex>
- template <typename T>
- class LockGuard
- {
- std::mutex& _m;
- T& _t;
- public:
- LockGuard(std::mutex& m, T& t)
- : _m(m)
- , _t(t)
- {
- _m.lock();
- }
- ~LockGuard()
- {
- _m.unlock();
- }
- T* operator->()
- {
- return &_t;
- }
- };
- template <typename T>
- class Mutex
- {
- std::mutex _mutex;
- T _value;
- public:
- Mutex()
- {
- }
- template <class... Args>
- Mutex(Args&&... args)
- : _value(T(args...))
- {
- }
- LockGuard<T> lock()
- {
- return LockGuard<T>(_mutex, _value);
- }
- };
- struct Test
- {
- int x;
- int y;
- Test(int xx, int yy)
- {
- x = xx;
- y = yy;
- }
- void func()
- {
- x++;
- }
- };
- int main()
- {
- Mutex<Test> am(12, 13);
- am.lock()->func();
- {
- auto lock = am.lock();
- lock->func();
- lock->func();
- }
- }
Add Comment
Please, Sign In to add comment