Guest User

Untitled

a guest
May 26th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. #include <mutex>
  2.  
  3. template <typename T>
  4. class LockGuard
  5. {
  6. std::mutex& _m;
  7. T& _t;
  8.  
  9. public:
  10. LockGuard(std::mutex& m, T& t)
  11. : _m(m)
  12. , _t(t)
  13. {
  14. _m.lock();
  15. }
  16.  
  17. ~LockGuard()
  18. {
  19. _m.unlock();
  20. }
  21.  
  22. T* operator->()
  23. {
  24. return &_t;
  25. }
  26. };
  27.  
  28. template <typename T>
  29. class Mutex
  30. {
  31. std::mutex _mutex;
  32. T _value;
  33.  
  34. public:
  35. Mutex()
  36. {
  37. }
  38.  
  39. template <class... Args>
  40. Mutex(Args&&... args)
  41. : _value(T(args...))
  42. {
  43. }
  44.  
  45. LockGuard<T> lock()
  46. {
  47. return LockGuard<T>(_mutex, _value);
  48. }
  49. };
  50.  
  51.  
  52. struct Test
  53. {
  54. int x;
  55. int y;
  56.  
  57. Test(int xx, int yy)
  58. {
  59. x = xx;
  60. y = yy;
  61. }
  62.  
  63. void func()
  64. {
  65. x++;
  66. }
  67. };
  68.  
  69. int main()
  70. {
  71. Mutex<Test> am(12, 13);
  72.  
  73. am.lock()->func();
  74.  
  75. {
  76. auto lock = am.lock();
  77. lock->func();
  78. lock->func();
  79. }
  80. }
Add Comment
Please, Sign In to add comment