-
Notifications
You must be signed in to change notification settings - Fork 0
/
spin_lock.hpp
44 lines (36 loc) · 933 Bytes
/
spin_lock.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
#pragma once
#include <atomic>
#include <utility>
class spin_lock {
std::atomic_flag _flag = ATOMIC_FLAG_INIT;
public:
void lock() {
while (_flag.test_and_set(std::memory_order_acq_rel))
asm volatile("pause");
}
bool try_lock() {
return !_flag.test_and_set(std::memory_order_acq_rel);
}
void unlock() {
_flag.clear(std::memory_order_release);
}
};
class spin_lock_backoff {
std::atomic_flag _flag = ATOMIC_FLAG_INIT;
public:
void lock() {
unsigned backoff = 0;
while (_flag.test_and_set(std::memory_order_acq_rel)) {
for(unsigned i = 0; i < (1u << backoff); i++) {
asm volatile("pause");
}
backoff++;
}
}
bool try_lock() {
return !_flag.test_and_set(std::memory_order_acq_rel);
}
void unlock() {
_flag.clear(std::memory_order_release);
}
};