-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.hpp
More file actions
76 lines (63 loc) · 1.82 KB
/
mutex.hpp
File metadata and controls
76 lines (63 loc) · 1.82 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
#pragma once
#include <atomic>
#include <cstdint>
#include <os/futex/futex.hpp>
namespace thread::sync {
// Satisfies the BasicLockable concept https://en.cppreference.com/w/cpp/named_req/BasicLockable
class Mutex {
struct State {
enum _ : uint32_t {
Unlocked = 0,
LockedNoWaiters = 1,
LockedHasWaiters = 2,
};
};
public:
void lock() {
if (FastPathLock()) {
return;
}
while (!SlowPathLock()) {
}
}
void unlock() {
if (UnlockFastPath()) {
return;
}
lock_.store(State::Unlocked, std::memory_order_release);
os::futex::WakeAll(reinterpret_cast<uint32_t*>(&lock_));
}
private:
bool CompareExchange(uint32_t expected, uint32_t desired, std::memory_order success) {
return lock_.compare_exchange_strong(expected, desired, success,
/* failure */ std::memory_order_relaxed);
}
bool FastPathLock() {
return CompareExchange(
/* expected */ State::Unlocked,
/* desired */ State::LockedNoWaiters,
/* success */ std::memory_order_acquire);
}
bool SlowPathLock() {
CompareExchange(
/* expected */ State::LockedNoWaiters,
/* desired */ State::LockedHasWaiters,
/* success */ std::memory_order_acquire);
os::futex::Wait(reinterpret_cast<uint32_t*>(&lock_), /* oldval */ State::LockedHasWaiters);
if (CompareExchange(
/* expected */ State::Unlocked,
/* desired */ State::LockedHasWaiters,
/* success */ std::memory_order_acquire)) {
return true;
}
return false;
}
bool UnlockFastPath() {
return CompareExchange(
/* expected */ State::LockedNoWaiters,
/* desired */ State::Unlocked,
/* success */ std::memory_order_release);
}
std::atomic<uint32_t> lock_{State::Unlocked};
};
} // namespace thread::sync