-
Notifications
You must be signed in to change notification settings - Fork 0
/
spinlock.h
48 lines (45 loc) · 1.04 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
47
48
#pragma once
#include <atomic>
#include <chrono>
#include <emmintrin.h>
#include <thread>
#include <immintrin.h>
#include <iostream>
class Guard {
friend class SpinLock;
public:
~Guard() {
mutex.clear(std::memory_order_release);
mutex.notify_one();
// std::cout << "unlocked by guard\n";
}
private:
Guard(std::atomic_flag &mutex) : mutex(mutex) {}
std::atomic_flag &mutex;
};
class SpinLock {
private:
std::atomic_flag mutex;
public:
Guard lock() {
while(true) {
while(mutex.test(std::memory_order_acquire)) _mm_pause();
if(!mutex.test_and_set(std::memory_order_acquire)) {
return Guard(mutex);
} 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();
}
};