-
Notifications
You must be signed in to change notification settings - Fork 7
/
ThreadLocks.hpp
120 lines (84 loc) · 2.16 KB
/
ThreadLocks.hpp
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#ifndef THREADLOCKS_HPP
#define THREADLOCKS_HPP
#include <atomic>
#include <algorithm>
#include <chrono>
#include <thread>
#ifdef __linux__
// Linux specific definitions
namespace OS_Specific
{
inline void thread_nano_sleep()
{
std::this_thread::sleep_for(std::chrono::nanoseconds(100));
}
}
#elif defined(__APPLE__)
// OSX specific definitions
namespace OS_Specific
{
inline void thread_nano_sleep()
{
std::this_thread::sleep_for(std::chrono::nanoseconds(100));
}
}
#else
// Windows OS specific definitions
#include <windows.h>
namespace OS_Specific
{
inline void thread_nano_sleep()
{
SwitchToThread();
}
}
#endif
class thread_lock
{
using Clock = std::chrono::steady_clock;
public:
thread_lock() {}
~thread_lock() { acquire(); }
// Non-copyable
thread_lock(const thread_lock&) = delete;
thread_lock& operator=(const thread_lock&) = delete;
void acquire()
{
for (int i = 0; i < 10; i++)
if (attempt())
return;
auto timeOut = Clock::now() + std::chrono::nanoseconds(10000);
while (Clock::now() < timeOut)
if (attempt())
return;
while (!attempt())
OS_Specific::thread_nano_sleep();
}
bool attempt() { return !m_atomic_lock.test_and_set(); }
void release() { m_atomic_lock.clear(); }
private:
std::atomic_flag m_atomic_lock = ATOMIC_FLAG_INIT;
};
// A generic lock holder using RAII
template <class T, void (T::*acquire_method)(), void (T::*release_method)()>
class lock_hold
{
public:
lock_hold() : m_lock(nullptr) {}
lock_hold(thread_lock *lock) : m_lock(lock) { if (m_lock) m_lock->*acquire_method(); }
~lock_hold() { if (m_lock) m_lock->release(); }
// Non-copyable
lock_hold(const lock_hold&) = delete;
lock_hold& operator=(const lock_hold&) = delete;
void release()
{
if (m_lock)
{
(m_lock->*release_method)();
m_lock = nullptr;
}
}
private:
thread_lock *m_lock;
};
#endif /* THREADLOCKS_HPP */