Lock Challenge Step 4
Syncmultiplethreadssharingaresource
LockGuard.h
Go to the documentation of this file.
1 
12 #ifndef _LOCK_G_H // header guard
13 #define _LOCK_G_H
14 
15 #include <mutex> // std::mutex, std::adopt_lock
16 
17 
18 
19 
20 namespace chal { // challenge namespace
21 
22  bool DEBUG = true;
23 
33  template<typename _Mutex>
34  class LockGuard
35  {
36  public:
37  typedef _Mutex mutex_type;
38 
39 
40  // no implicit constructor
41  explicit LockGuard(mutex_type& __m) : _M_device(__m) {
42  _M_device.lock();
43 
44  if(DEBUG) {
45  std::cerr << "LockGuard locked" << std::endl;
46  }
47  }
48 
49 
50  // calling thread owns mutex
51  LockGuard(mutex_type& __m, std::adopt_lock_t) : _M_device(__m) {
52 
53  if(DEBUG) {
54  std::cerr << "LockGuard adopted" << std::endl;
55  }
56  }
57 
58 
60  _M_device.unlock();
61 
62  if(DEBUG) {
63  std::cerr << "LockGuard unlocked" << std::endl;
64  }
65  }
66 
67  // generate compile error if copy attempted
68  // (supposed to be un-copyable)
69  LockGuard(const LockGuard&) = delete; // copy constructor
70  LockGuard& operator=(const LockGuard&) = delete; // copy assignment operator
71 
72  private:
73  mutex_type& _M_device;
74  };
75 }
76 
77 #endif
LockGuard(mutex_type &__m)
Definition: LockGuard.h:41
LockGuard & operator=(const LockGuard &)=delete
A movable scoped lock type.
Definition: LockGuard.h:34
_Mutex mutex_type
Definition: LockGuard.h:37
mutex_type & _M_device
Definition: LockGuard.h:73
Definition: LockGuard.h:20
bool DEBUG
Definition: LockGuard.h:22
LockGuard(mutex_type &__m, std::adopt_lock_t)
Definition: LockGuard.h:51