C++ 메모리 모델 | "동시성" 메모리 모델 가이드
이 글의 핵심
C++ 메모리 모델에 대한 실전 가이드입니다. 개념부터 실무 활용까지 예제와 함께 상세히 설명합니다.
메모리 모델이란?
멀티스레드 환경에서 메모리 접근 순서와 가시성 규칙
// 데이터 레이스 예시
int x = 0;
// 스레드 1
x = 1;
// 스레드 2
cout << x << endl; // 0? 1? 미정의!
happens-before
#include <atomic>
#include <thread>
atomic<bool> ready(false);
int data = 0;
void producer() {
data = 42; // A
ready.store(true, memory_order_release); // B
}
void consumer() {
while (!ready.load(memory_order_acquire)); // C
cout << data << endl; // D: 42 보장
}
// A happens-before B
// C synchronizes-with B
// B happens-before C
// A happens-before D
synchronizes-with
atomic<int> x(0);
atomic<int> y(0);
// 스레드 1
void thread1() {
x.store(1, memory_order_release); // A
}
// 스레드 2
void thread2() {
while (x.load(memory_order_acquire) == 0); // B
y.store(1, memory_order_release); // C
}
// A synchronizes-with B
// B happens-before C
실전 예시
예시 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 counter = 0;
void increment() {
SpinLock lock;
for (int i = 0; i < 1000; i++) {
lock.lock();
counter++;
lock.unlock();
}
}
int main() {
thread t1(increment);
thread t2(increment);
t1.join();
t2.join();
cout << counter << endl; // 2000
}
예시 2: 더블 체크 락킹
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;
예시 3: 생산자-소비자
#include <queue>
class SafeQueue {
private:
queue<int> q;
mutex mtx;
condition_variable cv;
public:
void push(int value) {
{
lock_guard<mutex> lock(mtx);
q.push(value);
}
cv.notify_one();
}
int pop() {
unique_lock<mutex> lock(mtx);
cv.wait(lock, [this] { return !q.empty(); });
int value = q.front();
q.pop();
return value;
}
};
void producer(SafeQueue& queue) {
for (int i = 0; i < 10; i++) {
queue.push(i);
cout << "생산: " << i << endl;
this_thread::sleep_for(chrono::milliseconds(100));
}
}
void consumer(SafeQueue& queue) {
for (int i = 0; i < 10; i++) {
int value = queue.pop();
cout << "소비: " << value << endl;
}
}
int main() {
SafeQueue queue;
thread t1(producer, ref(queue));
thread t2(consumer, ref(queue));
t1.join();
t2.join();
}
메모리 순서
Relaxed
atomic<int> counter(0);
void increment() {
counter.fetch_add(1, memory_order_relaxed);
}
// 순서 보장 없음, 가장 빠름
Acquire-Release
atomic<bool> ready(false);
int data = 0;
void producer() {
data = 42;
ready.store(true, memory_order_release);
}
void consumer() {
while (!ready.load(memory_order_acquire));
cout << data << endl; // 42 보장
}
Sequential Consistency
atomic<int> x(0);
atomic<int> y(0);
// 모든 스레드가 같은 순서로 봄
x.store(1, memory_order_seq_cst);
y.store(1, memory_order_seq_cst);
데이터 레이스
// ❌ 데이터 레이스
int counter = 0;
void increment() {
counter++; // 여러 스레드에서 (UB)
}
// ✅ atomic 사용
atomic<int> counter(0);
void increment() {
counter++; // 안전
}
// ✅ mutex 사용
int counter = 0;
mutex mtx;
void increment() {
lock_guard<mutex> lock(mtx);
counter++;
}
자주 발생하는 문제
문제 1: 잘못된 메모리 순서
// ❌ relaxed (데이터 레이스)
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가 아닐 수 있음!
}
// ✅ acquire-release
void producer() {
data = 42;
ready.store(true, memory_order_release);
}
void consumer() {
while (!ready.load(memory_order_acquire));
cout << data << endl; // 42 보장
}
문제 2: 가시성 문제
// ❌ 가시성 없음
bool flag = false;
void thread1() {
flag = true;
}
void thread2() {
while (!flag); // 무한 루프 가능!
}
// ✅ atomic 사용
atomic<bool> flag(false);
void thread1() {
flag.store(true);
}
void thread2() {
while (!flag.load());
}
문제 3: 순서 재배치
// 컴파일러/CPU가 재배치 가능
int x = 0;
int y = 0;
// 스레드 1
x = 1; // A
y = 1; // B
// 재배치: B가 A보다 먼저 실행될 수 있음!
// ✅ memory_order로 순서 보장
atomic<int> x(0);
atomic<int> y(0);
x.store(1, memory_order_release);
y.store(1, memory_order_release);
FAQ
Q1: 메모리 모델은 왜 중요한가요?
A: 멀티스레드 프로그램의 정확성을 보장합니다.
Q2: 메모리 순서는 어떻게 선택하나요?
A:
- 확실하지 않으면 seq_cst
- 성능이 중요하면 acquire-release
- 단순 카운터면 relaxed
Q3: happens-before란?
A: 한 연산이 다른 연산보다 먼저 실행되고 결과가 보임을 보장.
Q4: 데이터 레이스는?
A: 두 스레드가 동시에 같은 메모리에 접근하고 하나 이상이 쓰기인 경우.
Q5: 메모리 모델 디버깅은?
A: ThreadSanitizer 사용.
Q6: 메모리 모델 학습 리소스는?
A:
- “C++ Concurrency in Action” (Anthony Williams)
- cppreference.com
- “C++ Memory Model” (Herb Sutter)
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Memory Order | “메모리 순서” 가이드
- C++ Atomic | “메모리 순서” 완벽 가이드
- C++ Atomic Operations | “원자적 연산” 가이드
관련 글
- C++ Atomic |
- C++ Atomic Operations |
- C++ condition_variable 기초 |
- C++ 개발자를 위한 2주 완성 Go 언어(Golang) 마스터 커리큘럼
- C++ Lock-Free Programming |