-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpinLock.h
48 lines (38 loc) · 894 Bytes
/
SpinLock.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
#pragma once
#include <atomic>
#include <thread>
class SpinLock {
private:
std::atomic<bool> locked_;
public:
SpinLock() : locked_(false) {
}
void lock(bool yield = false) {
while (true) {
bool locked = this->locked_.load();
if (locked) {
// std::clog << "Locked" << std::endl;
if (yield) std::this_thread::yield();
continue;
}
if (locked_.compare_exchange_weak(locked, true))
break;
}
}
void unlock() {
locked_.store(false);
}
SpinLock(const SpinLock&) = delete;
SpinLock(SpinLock&&) = delete;
};
class RAIISpinLock {
private:
SpinLock& spinLock_;
public:
RAIISpinLock(SpinLock& spinLock) : spinLock_(spinLock) {
spinLock_.lock();
}
~RAIISpinLock() {
spinLock_.unlock();
}
};