C++ atomic

2021. 3. 30. 00:03·SW개발/C++
반응형

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
    */

반응형
저작자표시 (새창열림)

'SW개발 > C++' 카테고리의 다른 글

C++ 동시성 (Concurrency)  (0) 2021.03.30
C++ 멀티쓰레딩 (Multithreading)  (0) 2021.03.30
C++ mutex  (0) 2021.03.30
C++ 람다 함수 (Lambda Function)  (0) 2021.03.30
따라하며 배우는 C++ 19장  (0) 2021.03.30
'SW개발/C++' 카테고리의 다른 글
  • C++ 동시성 (Concurrency)
  • C++ 멀티쓰레딩 (Multithreading)
  • C++ mutex
  • C++ 람다 함수 (Lambda Function)
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (319)
      • SW개발 (268)
        • Java Spring (6)
        • C++ (186)
        • Python (21)
        • Linux (16)
        • 알고리즘 (13)
        • Git (4)
        • Embedded (1)
        • Raspberrypi (9)
        • React (3)
        • Web (2)
        • Windows Device Driver (6)
      • IT(개발아님) (46)
        • Windows (26)
        • MacOS (7)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    SunOS 5.1
    java
    로지텍 마우스 제스처
    unix
    윈도우
    windows
    스프링
    Workspace
    spring
    Solaris 10
    dism
    스프링 프레임워크 핵심 기술
    백기선
    mspaint
    MacOS
    시스템 복구
    logi options
    제외
    알림
    EXCLUDE
    Windows 11
    KakaoTalk
    그림판
    SFC
    윈도우 명령어
    vscode
    citrix workspace
    맥북 카카오톡 알림 안뜸
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ atomic
상단으로

티스토리툴바