-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmutex.hpp
46 lines (36 loc) · 828 Bytes
/
mutex.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
#pragma once
#include <utils/object.hpp>
#include <atomic>
#include <cassert>
#include <thread>
class Mutex : noncopyable
{
public:
Mutex() {}
~Mutex() { assert(!m_atomic_flag.test_and_set()); }
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 MutexLocker : noncopyable
{
Mutex *m_mutex = nullptr;
public:
MutexLocker(Mutex *mutex)
: m_mutex(mutex)
{
assert(m_mutex);
m_mutex->lock();
}
~MutexLocker()
{
assert(m_mutex);
m_mutex->unlock();
}
};