-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathObjecLevelLock.h
More file actions
82 lines (73 loc) · 2.38 KB
/
ObjecLevelLock.h
File metadata and controls
82 lines (73 loc) · 2.38 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* ObjectLevelLock.h
*
* Created on: Nov 13, 2021
* Author: <a href="mailto:damirlj@yahoo.com">Damir Ljubic</a>
*/
#ifndef AIRPLAYSERVICE_OBJECLEVELLOCK_H
#define AIRPLAYSERVICE_OBJECLEVELLOCK_H
#include <mutex>
namespace utils::locking
{
/**
* Policy-based design.
* Object level locking: each instance has it's on dedicated
* locking mechanism (mutex)
*
* usage:
* template <typename LockingPolicy>
* class Host : private LockingPolicy
* {
* public:
* void f()
* {
* typename LockingPolicy::Lock lock{*this};
* ...
* }
* };
*/
class ObjectLevelLock
{
public:
using lock_type = std::mutex;
ObjectLevelLock() = default;
~ObjectLevelLock() = default;
ObjectLevelLock(const ObjectLevelLock&) = delete;
ObjectLevelLock& operator=(const ObjectLevelLock& ) = delete;
class Lock;
friend class Lock;
/**
* Idea with the inner class Lock is for implementing
* the policy-based design, referring at the client side to the same
* (name) inner class
* 'typename T::Lock lock{*this};'
* independent of the locking policy implementation behind
*
*/
class Lock final
{
public:
/**
* C-tor
* @param lock We will pass actually the reference to the "Host" class!
* @note This will work only if we impose parameterized inheritance
* template <typename LockingPolicy>
* class Host : private LockingPolicy
* {};
*/
explicit Lock(const ObjectLevelLock& lock) noexcept: m_objectLock(lock)
{
m_objectLock.m_lock.lock();
}
~Lock()
{
m_objectLock.m_lock.unlock();
}
private:
const ObjectLevelLock& m_objectLock;
};
private:
mutable lock_type m_lock;
};
}
#endif //AIRPLAYSERVICE_OBJECLEVELLOCK_H