mirror of
https://github.com/changkun/modern-cpp-tutorial.git
synced 2025-12-17 04:34:40 +03:00
16
exercises/7/7.1/Makefile
Normal file
16
exercises/7/7.1/Makefile
Normal file
@@ -0,0 +1,16 @@
|
||||
#
|
||||
# Makefile
|
||||
#
|
||||
# exercise solution 7.1 - chapter 7
|
||||
# modern cpp tutorial
|
||||
#
|
||||
# created by changkun at changkun.de/modern-cpp
|
||||
#
|
||||
|
||||
all: $(patsubst %.cpp, %.out, $(wildcard *.cpp))
|
||||
|
||||
%.out: %.cpp Makefile
|
||||
clang++ $< -o $@ -std=c++2a -pedantic
|
||||
|
||||
clean:
|
||||
rm *.out
|
||||
44
exercises/7/7.2.mutex.cpp
Normal file
44
exercises/7/7.2.mutex.cpp
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user