C++/Library 2021. 3. 30. 00:03

atomic

  • <atomic> 라이브러리

  • 보장하고 싶은 변수를 atomic<type> 형식으로 정의하면 된다.

  • 성능이 느려진다.

    • 성능을 위해 mutex를 사용하는 것 같다.

예제

  • atomic을 사용하지 않은 예제

    #include <iostream>
    #include <thread>
    #include <chrono>
    
    int         main()
    {
        using namespace std;
    
        int shared_memory(0);
    
        auto count_func = [&]() {
            for (int i = 0; i < 1000; ++i)
            {
                this_thread::sleep_for(chrono::milliseconds(1));
                shared_memory++;
            }
        };
    
        thread t1 = thread(count_func);
        thread t2 = thread(count_func);
    
        t1.join();
        t2.join();
    
        cout << "Value is " << shared_memory << endl;
    }
    
    /* stdout stderr
    Value is 1997
    */
    • 값이 2000이 아닌 1997이 나온 것을 볼 수 있다.
  • atomic을 사용한 예제

    • <atomic> 라이브러리를 포함하지 않아도 사용할 수 있었다.

    • 여기서 shared_memory++atomic 클래스에서 오버로딩한 연산자를 사용한다.

    #include <iostream>
    #include <thread>
    #include <chrono>
    #include <atomic>
    
    int         main()
    {
        using namespace std;
    
        atomic<int> shared_memory(0);
    
        auto count_func = [&]() {
            for (int i = 0; i < 1000; ++i)
            {
                this_thread::sleep_for(chrono::milliseconds(1));
                shared_memory++;
            }
        };
    
        thread t1 = thread(count_func);
        thread t2 = thread(count_func);
    
        t1.join();
        t2.join();
    
        cout << "Value is " << shared_memory << endl;
    }
    
    /* stdout stderr
    Value is 2000
    */

'C++ > Library' 카테고리의 다른 글

C++ future  (0) 2021.03.30
C++ 멀티쓰레딩 (Multithreading)  (0) 2021.03.30
C++ mutex  (0) 2021.03.30
C++ 파일 임의 위치 접근  (0) 2021.03.29
C++ fstream  (0) 2021.03.29