C++ Atomic | "메모리 순서" 완벽 가이드
이 글의 핵심
C++ Atomic에 대해 정리한 개발 블로그 글입니다. #include <atomic> #include <thread> using namespace std;
atomic 기본
#include <atomic>
#include <thread>
using namespace std;
atomic<int> counter(0);
void increment() {
for (int i = 0; i < 1000; i++) {
counter++; // 원자적 연산
}
}
int main() {
thread t1(increment);
thread t2(increment);
t1.join();
t2.join();
cout << counter << endl; // 2000 (항상 정확)
}
atomic vs mutex
여러 스레드가 같은 메모리를 볼 때의 질서는 mutex로 임계 구역을 잡는 방식과, 원자 변수·메모리 순서로 맞추는 방식이 대표적입니다. Java의 volatile·Atomic*도 같은 계열의 문제를 다루고, Rust의 Mutex·원자 타입은 소유권과 묶여 다른 모양을 띱니다.
// mutex 사용
mutex mtx;
int counter = 0;
void incrementMutex() {
for (int i = 0; i < 1000; i++) {
lock_guard<mutex> lock(mtx);
counter++;
}
}
// atomic 사용 (더 빠름)
atomic<int> atomicCounter(0);
void incrementAtomic() {
for (int i = 0; i < 1000; i++) {
atomicCounter++;
}
}
메모리 순서 (Memory Order)
memory_order_relaxed
atomic<int> x(0);
atomic<int> y(0);
// 스레드 1
void thread1() {
x.store(1, memory_order_relaxed);
y.store(1, memory_order_relaxed);
}
// 스레드 2
void thread2() {
while (y.load(memory_order_relaxed) == 0);
// x가 1이라는 보장 없음!
cout << x.load(memory_order_relaxed) << endl;
}
memory_order_acquire/release
atomic<int> data(0);
atomic<bool> ready(false);
// 생산자
void producer() {
data.store(42, memory_order_relaxed);
ready.store(true, memory_order_release); // release
}
// 소비자
void consumer() {
while (!ready.load(memory_order_acquire)); // acquire
cout << data.load(memory_order_relaxed) << endl; // 42 보장
}
memory_order_seq_cst (기본값)
atomic<int> x(0);
atomic<int> y(0);
// 순차 일관성 보장
x.store(1, memory_order_seq_cst);
y.store(1, memory_order_seq_cst);
// 모든 스레드가 같은 순서로 봄
실전 예시
예시 1: 스핀락
class SpinLock {
private:
atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock() {
while (flag.test_and_set(memory_order_acquire)) {
// 스핀 (대기)
}
}
void unlock() {
flag.clear(memory_order_release);
}
};
int main() {
SpinLock spinlock;
int counter = 0;
auto increment = [&]() {
for (int i = 0; i < 1000; i++) {
spinlock.lock();
counter++;
spinlock.unlock();
}
};
thread t1(increment);
thread t2(increment);
t1.join();
t2.join();
cout << counter << endl; // 2000
}
예시 2: Lock-Free 스택
template<typename T>
class LockFreeStack {
private:
struct Node {
T data;
Node* next;
Node(T d) : data(d), next(nullptr) {}
};
atomic<Node*> head;
public:
LockFreeStack() : head(nullptr) {}
void push(T value) {
Node* newNode = new Node(value);
newNode->next = head.load(memory_order_relaxed);
while (!head.compare_exchange_weak(
newNode->next, newNode,
memory_order_release,
memory_order_relaxed
));
}
bool pop(T& result) {
Node* oldHead = head.load(memory_order_relaxed);
while (oldHead && !head.compare_exchange_weak(
oldHead, oldHead->next,
memory_order_acquire,
memory_order_relaxed
));
if (oldHead) {
result = oldHead->data;
delete oldHead;
return true;
}
return false;
}
};
int main() {
LockFreeStack<int> stack;
thread t1([&]() {
for (int i = 0; i < 100; i++) {
stack.push(i);
}
});
thread t2([&]() {
int value;
for (int i = 0; i < 50; i++) {
if (stack.pop(value)) {
cout << value << " ";
}
}
});
t1.join();
t2.join();
}
예시 3: 더블 체크 락킹
class Singleton {
private:
static atomic<Singleton*> instance;
static mutex mtx;
Singleton() {}
public:
static Singleton* getInstance() {
Singleton* tmp = instance.load(memory_order_acquire);
if (tmp == nullptr) {
lock_guard<mutex> lock(mtx);
tmp = instance.load(memory_order_relaxed);
if (tmp == nullptr) {
tmp = new Singleton();
instance.store(tmp, memory_order_release);
}
}
return tmp;
}
};
atomic<Singleton*> Singleton::instance(nullptr);
mutex Singleton::mtx;
compare_exchange
atomic<int> value(0);
int expected = 0;
int desired = 10;
// 약한 버전 (spurious failure 가능)
if (value.compare_exchange_weak(expected, desired)) {
cout << "성공" << endl;
} else {
cout << "실패, 현재 값: " << expected << endl;
}
// 강한 버전 (spurious failure 없음)
if (value.compare_exchange_strong(expected, desired)) {
cout << "성공" << endl;
}
메모리 순서 정리
| 순서 | 설명 | 사용 시나리오 |
|---|---|---|
| relaxed | 순서 보장 없음 | 카운터 |
| acquire | 이후 읽기/쓰기 재배치 방지 | 락 획득 |
| release | 이전 읽기/쓰기 재배치 방지 | 락 해제 |
| acq_rel | acquire + release | RMW 연산 |
| seq_cst | 순차 일관성 (기본값) | 확실하지 않을 때 |
자주 발생하는 문제
문제 1: 잘못된 메모리 순서
// ❌ 데이터 레이스
atomic<bool> ready(false);
int data = 0;
void producer() {
data = 42;
ready.store(true, memory_order_relaxed); // 잘못됨!
}
void consumer() {
while (!ready.load(memory_order_relaxed));
cout << data << endl; // 42가 아닐 수 있음!
}
// ✅ 올바른 순서
void producer() {
data = 42;
ready.store(true, memory_order_release);
}
void consumer() {
while (!ready.load(memory_order_acquire));
cout << data << endl; // 42 보장
}
문제 2: ABA 문제
// ❌ ABA 문제
atomic<Node*> head;
void pop() {
Node* oldHead = head.load();
// 여기서 다른 스레드가 pop, push 할 수 있음
head.compare_exchange_strong(oldHead, oldHead->next);
// oldHead가 다른 노드일 수 있음!
}
// ✅ 태그 포인터 사용
struct TaggedPointer {
Node* ptr;
uintptr_t tag;
};
atomic<TaggedPointer> head;
문제 3: 잘못된 atomic 사용
// ❌ atomic이 아닌 타입
struct Big {
int data[100];
};
atomic<Big> a; // 컴파일 에러 또는 lock 기반
// ✅ 작은 타입만
atomic<int> a;
atomic<bool> b;
atomic<void*> c;
성능 고려사항
// relaxed (가장 빠름)
counter.fetch_add(1, memory_order_relaxed);
// acquire/release (중간)
flag.store(true, memory_order_release);
// seq_cst (가장 느림, 기본값)
counter.fetch_add(1, memory_order_seq_cst);
FAQ
Q1: atomic은 언제 사용하나요?
A:
- 간단한 카운터
- 플래그
- Lock-free 자료구조
Q2: atomic vs mutex?
A:
- atomic: 간단한 연산, 빠름
- mutex: 복잡한 연산, 여러 변수
Q3: memory_order는 어떻게 선택하나요?
A:
- 확실하지 않으면 seq_cst (기본값)
- 성능이 중요하면 acquire/release
- 단순 카운터면 relaxed
Q4: Lock-free는 항상 빠른가요?
A: 아니요. 경합이 많으면 mutex가 더 빠를 수 있습니다.
Q5: atomic 디버깅은?
A:
- ThreadSanitizer 사용
- 로깅 추가
- 단순한 케이스부터 테스트
Q6: atomic 학습 리소스는?
A:
- “C++ Concurrency in Action” (Anthony Williams)
- cppreference.com
- Preshing on Programming 블로그
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Memory Order | “메모리 순서” 가이드
- C++ Atomic Operations | “원자적 연산” 가이드
- C++ Lock-Free Programming | “락 프리 프로그래밍” 가이드
관련 글
- C++ Atomic Operations |
- C++ Lock-Free Programming |
- C++ Memory Order |
- C++ Lock-Free 프로그래밍 실전 | CAS·ABA·메모리 순서·고성능 큐 [#34-3]
- C++ Lock-Free 프로그래밍 실전 | CAS·ABA·메모리 순서·고성능 큐 [#51-5]