book: revision of ch07 & finish atomics

Update #2
This commit is contained in:
Changkun Ou
2019-07-19 10:59:01 +02:00
parent fdb34b80e5
commit 677f74b691
12 changed files with 327 additions and 81 deletions

44
exercises/7/7.2.mutex.cpp Normal file
View File

@@ -0,0 +1,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;
}