std::atomic

programming/C++ 2013. 2. 18. 06:26

1. 두가지 효과

하나, atomic operation을 제공한다.

둘, default memory order는 sequential consistency이다. 따라서, atomic operation이 프로그램된 순서대로 일어나는 것이 보장된다. (이를 변경할 수 있다. std::memory_order_relaxed)

 

2. 항상 초기화할 것.

std::atomic<bool> readyFlag(false);

(std::atomic<bool> readyFlag; std::atomic_init(&readyFlag, false); 이렇게 할 수도 있으나 뭐하러 그러나?)

 

3. store()와 load()

store()는 소위 release operation이다. 즉, prior memory operation들(atomic이든 아니든)이 다른 thread에 visible하게 만든다.

반면에, load()는 acquire operation이다. 즉, following memory operation들(atomic이든 아니든)이 visible하게 만든다.

 

 

* Example (from "The C++ Standard Library, 2nd edition")

#include <atomic>    // for atomics
#include <future>    // for async() and futures
#include <thread>    // for this_thread
#include <chrono>    // for durations
#include <iostream> 

long data; 
std::atomic<bool> readyFlag(false); 

void provider () 
{ 
    // after reading a character 
    std::cout << "<return>" << std::endl;
    std::cin.get(); 

    // provide some data 
    data = 42; 

    // and signal readiness 
    readyFlag.store(true); 
} 

void consumer () 
{ 
    // wait for readiness and do something else 
    while (!readyFlag.load()) { 
        std::cout.put('.').flush(); 
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    } 

    // and process provided data 
    std::cout << "\nvalue : " << data << std::endl; 
} 

int main() 
{ 
    // start provider and consumer 
    auto p = std::async(std::launch::async,provider);
    auto c = std::async(std::launch::async,consumer);
} 

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

Explicit conversion  (0) 2013.02.19
Online C++ compilers  (0) 2013.02.18
C++11 cheat sheet  (0) 2013.02.18
Universal reference  (0) 2013.02.18
shared_ptr, unique_ptr  (0) 2013.02.18
Posted by 무한자전거
,