Lock Challenge Step 3
Syncmultiplethreadssharingaresource
LockGuard.h
Go to the documentation of this file.
1 #ifndef _LOCK_G_H // header guard
2 #define _LOCK_G_H
3 
4 #include <mutex> // std::mutex, std::adopt_lock
5 
6 
7 
8 namespace chal { // challenge namespace
9 
10 
11  bool DEBUG = true;
12 
13 
23  template<typename _Mutex>
24  class LockGuard
25  {
26  public:
27  typedef _Mutex mutex_type;
28 
29 
30  // no implicit constructor
31  explicit LockGuard(mutex_type& __m) : _M_device(__m) {
32  _M_device.lock();
33 
34  if(DEBUG) {
35  std::cout << "LockGuard locked" << std::endl;
36  }
37  }
38 
39 
40  // calling thread owns mutex
41  LockGuard(mutex_type& __m, std::adopt_lock_t) : _M_device(__m) {
42 
43  if(DEBUG) {
44  std::cout << "LockGuard adopted" << std::endl;
45  }
46  }
47 
48 
50  _M_device.unlock();
51 
52  if(DEBUG) {
53  std::cout << "LockGuard unlocked" << std::endl;
54  }
55  }
56 
57  // generate compile error if copy attempted
58  // (supposed to be un-copyable)
59  LockGuard(const LockGuard&) = delete; // copy constructor
60  LockGuard& operator=(const LockGuard&) = delete; // copy assignment operator
61 
62  private:
63  mutex_type& _M_device;
64  };
65 }
66 
67 #endif
LockGuard(mutex_type &__m)
Definition: LockGuard.h:31
LockGuard & operator=(const LockGuard &)=delete
A movable scoped lock type.
Definition: LockGuard.h:24
_Mutex mutex_type
Definition: LockGuard.h:27
mutex_type & _M_device
Definition: LockGuard.h:63
Definition: LockGuard.h:8
bool DEBUG
turn on debug messages
Definition: LockGuard.h:11
LockGuard(mutex_type &__m, std::adopt_lock_t)
Definition: LockGuard.h:41