C++/따배C++ 19강 모던 C++ 기능들
[C++/CPP] 19.04 Race Condition and std::atomic, std::scoped_lock
polarcompass
2021. 12. 12. 22:23
728x90
#include<iostream>
#include<string>
#include<thread>
#include<chrono>
#include<vector>
#include<mutex>
#include<atomic>
using namespace std;
mutex mtx;
int main()
{
// atomic shared memory
// atomic<int> shm(0);
// mutex condition
int shm(0);
// lambda function
auto count_func = [&](){
for (int i = 0; i < 1000; ++i)
{
// 어떤 계산이 복잡한 코드가 들어있는 것을 가정한 코드
this_thread::sleep_for(chrono::milliseconds(1));
// mtx.lock();
// std::lock_guard lock(mtx); // lock(), unlock() 포함 코드
// shm++;
// mtx.unlock();
// 권장되는 코드
std::scoped_lock lock(mtx);
shm++;
// atomic condition
// shm.fetch_add(1);
mtx.unlock();
}
};
thread t1 = thread(count_func);
thread t2 = thread(count_func);
t1.join();
t2.join();
cout << "After" << endl;
cout << shm << endl;
return 0;
}
728x90