forked from changkun/modern-cpp-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7.2.mutex.cpp
More file actions
44 lines (35 loc) · 734 Bytes
/
7.2.mutex.cpp
File metadata and controls
44 lines (35 loc) · 734 Bytes
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
#include <atomic>
#include <thread>
#include <iostream>
class mutex {
std::atomic<bool> flag{false};
public:
void lock()
{
while (flag.exchange(true, std::memory_order_relaxed));
std::atomic_thread_fence(std::memory_order_acquire);
}
void unlock()
{
std::atomic_thread_fence(std::memory_order_release);
flag.store(false, std::memory_order_relaxed);
}
};
int a = 0;
int main() {
mutex mtx_a;
std::thread t1([&](){
mtx_a.lock();
a += 1;
mtx_a.unlock();
});
std::thread t2([&](){
mtx_a.lock();
a += 2;
mtx_a.unlock();
});
t1.join();
t2.join();
std::cout << a << std::endl;
return 0;
}