atomic_fetch_sub
atomic_fetch_sub (원자적으로 빼기)
atomic 객체의 값에서 원자적으로 값을 빼고, 빼기 전의 이전 값을 반환하는 연산이에요. <atomic> 헤더, C++11부터.
출처: cppreference
본문
atomic_fetch_sub는 obj가 가리키는 값에서 arg를 원자적으로 빼고, 빼기 전에 obj가 들고 있던 값을 돌려줘요.
template< class T >
T atomic_fetch_sub( std::atomic<T>* obj,
typename std::atomic<T>::difference_type arg ) noexcept; // (1)
arg의 타입이 difference_type이라는 점이 특징이에요. 포인터 특수화에서는 ptr - arg처럼 요소 개수 단위로 앞으로 이동하는 효과를 줘요.
_explicit 버전은 메모리 순서를 직접 지정해요.
template< class T >
T atomic_fetch_sub_explicit( std::atomic<T>* obj,
typename std::atomic<T>::difference_type arg,
std::memory_order order ) noexcept; // (3)
- 읽기-수정-쓰기(RMW)를 하나의 원자 연산으로 수행해요.
- 기본 메모리 순서는
std::memory_order_seq_cst예요.
fetch_add의 반대 연산으로, 분산 카운터를 내릴 때나 리소스 해제 횟수를 세는 데 쓰여요.
std::atomic<int> counter{10};
int before = std::atomic_fetch_sub(&counter, 1); // 이전 값 10을 얻고 1 감소
fetch_add와 짝을 이루고, 카운트 다운 동기화 패턴에서 자주 사용돼요.