-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathspinmutex.hpp
54 lines (44 loc) · 1.17 KB
/
spinmutex.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
44
45
46
47
48
49
50
51
52
53
54
#pragma once
#include <utils/object.hpp>
#include <atomic>
#include <cassert>
#include <iostream>
#include <thread>
class SpinMutex : noncopyable
{
public:
SpinMutex() { m_atomic_flag.clear(std::memory_order_release); }
~SpinMutex()
{
if (m_atomic_flag.test_and_set(std::memory_order_acquire)) {
assert(false && "SpinLock destroyed while locked!");
std::cerr << "Error: SpinLock destroyed while locked!" << std::endl;
}
m_atomic_flag.clear(std::memory_order_release);
}
void lock()
{
while (m_atomic_flag.test_and_set(std::memory_order_acquire)) {
std::this_thread::yield(); // 有这一行,就是自旋锁;没有这一行,就是互斥锁(忙等待)
}
}
void unlock() { m_atomic_flag.clear(std::memory_order_release); }
private:
std::atomic_flag m_atomic_flag;
};
class SpinMutexLocker : noncopyable
{
SpinMutex *m_mutex = nullptr;
public:
SpinMutexLocker(SpinMutex *mutex)
: m_mutex(mutex)
{
assert(m_mutex);
m_mutex->lock();
}
~SpinMutexLocker()
{
assert(m_mutex);
m_mutex->unlock();
}
};