-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLockGuard.h
67 lines (47 loc) · 1.87 KB
/
LockGuard.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#ifndef _LOCK_G_H // header guard
#define _LOCK_G_H
#include <mutex> // std::mutex, std::adopt_lock
namespace chal { // challenge namespace
bool DEBUG = true; ///< turn on debug messages
/// \brief A movable scoped lock type.
///
/// \note This class has been kept as identical to std::lock_guard as possible
///
/// A unique_lock controls mutex ownership within a scope. Ownership of the
/// mutex can be delayed until after construction and can be transferred
/// to another unique_lock by move construction or move assignment. If a
/// mutex lock is owned when the destructor runs ownership will be released.
///
template<typename _Mutex> ///< returns type determined by calling function
class LockGuard
{
public:
typedef _Mutex mutex_type;
// no implicit constructor
explicit LockGuard(mutex_type& __m) : _M_device(__m) {
_M_device.lock();
if(DEBUG) {
std::cout << "LockGuard locked" << std::endl;
}
}
// calling thread owns mutex
LockGuard(mutex_type& __m, std::adopt_lock_t) : _M_device(__m) {
if(DEBUG) {
std::cout << "LockGuard adopted" << std::endl;
}
}
~LockGuard() {
_M_device.unlock();
if(DEBUG) {
std::cout << "LockGuard unlocked" << std::endl;
}
}
// generate compile error if copy attempted
// (supposed to be un-copyable)
LockGuard(const LockGuard&) = delete; // copy constructor
LockGuard& operator=(const LockGuard&) = delete; // copy assignment operator
private:
mutex_type& _M_device;
};
}
#endif