-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathspinlock.h
46 lines (42 loc) · 1 KB
/
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
#pragma once
#include <atomic>
#include <mutex>
#if defined(__aarch64__)
#else
#include <emmintrin.h>
#include <immintrin.h>
#include <xmmintrin.h>
#endif
class SpinLock {
private:
std::atomic_flag mutex;
public:
void lock() {
while(true) {
while(mutex.test(std::memory_order_acquire)) {
#if defined(__aarch64__)
asm volatile("yield" ::: "memory");
#else
_mm_pause();
#endif
}
if(!mutex.test_and_set(std::memory_order_acquire)) {
return;
} else {
mutex.wait(true);
// std::this_thread::yield();
}
}
}
bool try_lock() {
return mutex.test_and_set()==false;
}
void unlock() {
mutex.clear(std::memory_order_release);
mutex.notify_one();
}
bool is_locked() {
return mutex.test();
}
};
typedef std::lock_guard<SpinLock> Guard;