250x250
Notice
Recent Posts
«   2024/07   »
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
관리 메뉴

일상 코딩

[C++/CPP] 19.04 Race Condition and std::atomic, std::scoped_lock 본문

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