atomic_atomic
atomic_atomic (원자적 타입)
std::atomic은 타입의 값을 원자적으로 조작하는 클래스 템플릿이에요. 다중 스레드에서 데이터 레이스 없이 값을 읽고 쓸 수 있게 해요.
출처: cppreference
본문
std::atomic은 <atomic> 헤더에 정의된 클래스 템플릿이에요.
template< class T >
struct atomic;
T는 trivially copyable이어야 해요. std::atomic의 객체를 만들면 그 값에 대한 연산(로드, 저장, 교환, fetch 연산, CAS 등)이 원자적으로 수행돼요.
주요 멤버 함수
load/store— 값을 원자적으로 읽고 써요.exchange— 값을 저장하고 이전 값을 반환해요.fetch_add/fetch_sub/fetch_and등 — 원자적 산술/논리 연산 (정수·포인터).compare_exchange_weak/compare_exchange_strong— CAS 연산.wait/notify_one/notify_all— 대기/알림 (C++20).is_lock_free— 락 프리 여부 확인.
std::atomic은 복사가 불가능해요. 정수, 포인터, 열거형 등 특수화가 존재해요.
예제 (Example)
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main()
{
std::atomic<int> counter{0};
std::vector<std::thread> ts;
for (int i = 0; i < 10; ++i)
ts.emplace_back([&]{ for (int j = 0; j < 1000; ++j)
counter.fetch_add(1); });
for (auto& t : ts) t.join();
std::cout << counter.load() << '\n'; // 10000
}