C++ shared_mutex | "읽기-쓰기 락" 가이드

C++ shared_mutex | "읽기-쓰기 락" 가이드

이 글의 핵심

std::shared_mutex(C++17)는 뮤텍스처럼 쓰기 시 배타 잠금을 쓰면서, 읽기 시에는 shared_lock으로 여러 스레드가 동시에 읽을 수 있게 합니다. scoped_lock은 배타 잠금용이고, 데이터 레이스·뮤텍스·스레드 기초를 먼저 보면 좋습니다.

shared_mutex란?

std::shared_mutex(C++17)는 뮤텍스처럼 쓰기 시 배타 잠금을 쓰면서, 읽기 시에는 shared_lock으로 여러 스레드가 동시에 읽을 수 있게 합니다. scoped_lock은 배타 잠금용이고, 데이터 레이스·뮤텍스·스레드 기초를 먼저 보면 좋습니다.

shared_mutex vs mutex 비교

구분mutexshared_mutex
읽기 동시성❌ 한 번에 1개✅ 여러 스레드 동시
쓰기 동시성❌ 한 번에 1개❌ 한 번에 1개
읽기-쓰기 충돌❌ 블로킹❌ 블로킹
사용 시나리오읽기/쓰기 비슷읽기 >> 쓰기
오버헤드낮음약간 높음
C++ 버전C++11C++17
#include <shared_mutex>
#include <map>
using namespace std;

class ThreadSafeMap {
private:
    map<int, string> data;
    mutable shared_mutex mtx;
    
public:
    // 읽기 (공유)
    string get(int key) const {
        shared_lock<shared_mutex> lock(mtx);
        auto it = data.find(key);
        return it != data.end() ? it->second : "";
    }
    
    // 쓰기 (배타)
    void set(int key, const string& value) {
        unique_lock<shared_mutex> lock(mtx);
        data[key] = value;
    }
};

락 동작 다이어그램

graph TD
    A[Thread Access] --> B{Operation}
    
    B -->|Read| C[shared_lock]
    C --> D{Other Thread?}
    D -->|Reading| E[✅ Acquire]
    D -->|Writing| F[⏳ Wait]
    D -->|None| E
    
    B -->|Write| G[unique_lock]
    G --> H{Other Thread?}
    H -->|Reading| I[⏳ Wait]
    H -->|Writing| I
    H -->|None| J[✅ Acquire]

기본 사용법

#include <shared_mutex>

shared_mutex mtx;
int counter = 0;

void reader() {
    shared_lock<shared_mutex> lock(mtx);  // 공유 락
    cout << "값: " << counter << endl;
}

void writer() {
    unique_lock<shared_mutex> lock(mtx);  // 배타 락
    counter++;
}

shared_lock vs unique_lock

락 타입 비교

락 타입용도동시 접근다른 shared_lock다른 unique_lock
shared_lock읽기✅ 여러 스레드✅ 허용❌ 블로킹
unique_lock쓰기❌ 배타적❌ 블로킹❌ 블로킹
lock_guard쓰기❌ 배타적❌ 블로킹❌ 블로킹
// shared_lock: 읽기 (여러 스레드 동시 가능)
shared_lock<shared_mutex> slock(mtx);

// unique_lock: 쓰기 (배타적)
unique_lock<shared_mutex> ulock(mtx);

// lock_guard도 사용 가능 (배타)
lock_guard<shared_mutex> lock(mtx);

동시 접근 시나리오

gantt
    title shared_mutex 동시성 타임라인
    dateFormat X
    axisFormat %L
    
    section 스레드1
    읽기 (shared_lock) :0, 100
    
    section 스레드2
    읽기 (shared_lock) :0, 100
    
    section 스레드3
    읽기 (shared_lock) :0, 100
    
    section 스레드4
    쓰기 대기 :0, 100
    쓰기 (unique_lock) :100, 150
    
    section 스레드5
    읽기 대기 :100, 150
    읽기 (shared_lock) :150, 200

실전 예시

예시 1: 캐시

#include <unordered_map>

class Cache {
private:
    unordered_map<string, string> data;
    mutable shared_mutex mtx;
    
public:
    // 읽기 (동시 접근 가능)
    optional<string> get(const string& key) const {
        shared_lock<shared_mutex> lock(mtx);
        
        auto it = data.find(key);
        if (it != data.end()) {
            return it->second;
        }
        return nullopt;
    }
    
    // 쓰기 (배타적)
    void put(const string& key, const string& value) {
        unique_lock<shared_mutex> lock(mtx);
        data[key] = value;
    }
    
    // 읽기 후 쓰기
    string getOrCompute(const string& key) {
        // 먼저 읽기 시도
        {
            shared_lock<shared_mutex> lock(mtx);
            auto it = data.find(key);
            if (it != data.end()) {
                return it->second;
            }
        }
        
        // 없으면 계산 후 쓰기
        string value = "computed_" + key;
        
        {
            unique_lock<shared_mutex> lock(mtx);
            data[key] = value;
        }
        
        return value;
    }
};

int main() {
    Cache cache;
    
    // 쓰기 스레드
    thread writer([&]() {
        for (int i = 0; i < 10; i++) {
            cache.put("key" + to_string(i), "value" + to_string(i));
            this_thread::sleep_for(chrono::milliseconds(100));
        }
    });
    
    // 읽기 스레드 (여러 개)
    vector<thread> readers;
    for (int i = 0; i < 5; i++) {
        readers.emplace_back([&, i]() {
            for (int j = 0; j < 20; j++) {
                auto value = cache.get("key" + to_string(j % 10));
                if (value) {
                    cout << "스레드 " << i << ": " << *value << endl;
                }
                this_thread::sleep_for(chrono::milliseconds(50));
            }
        });
    }
    
    writer.join();
    for (auto& t : readers) {
        t.join();
    }
}

예시 2: 설정 관리자

class ConfigManager {
private:
    unordered_map<string, string> config;
    mutable shared_mutex mtx;
    
public:
    // 읽기
    string get(const string& key) const {
        shared_lock<shared_mutex> lock(mtx);
        auto it = config.find(key);
        return it != config.end() ? it->second : "";
    }
    
    // 쓰기
    void set(const string& key, const string& value) {
        unique_lock<shared_mutex> lock(mtx);
        config[key] = value;
    }
    
    // 일괄 읽기
    unordered_map<string, string> getAll() const {
        shared_lock<shared_mutex> lock(mtx);
        return config;
    }
    
    // 일괄 쓰기
    void setAll(const unordered_map<string, string>& newConfig) {
        unique_lock<shared_mutex> lock(mtx);
        config = newConfig;
    }
};

예시 3: 통계 수집기

class Statistics {
private:
    long long totalRequests = 0;
    long long successCount = 0;
    long long errorCount = 0;
    mutable shared_mutex mtx;
    
public:
    // 쓰기
    void recordRequest(bool success) {
        unique_lock<shared_mutex> lock(mtx);
        totalRequests++;
        if (success) {
            successCount++;
        } else {
            errorCount++;
        }
    }
    
    // 읽기
    double getSuccessRate() const {
        shared_lock<shared_mutex> lock(mtx);
        if (totalRequests == 0) return 0.0;
        return 100.0 * successCount / totalRequests;
    }
    
    void printStats() const {
        shared_lock<shared_mutex> lock(mtx);
        cout << "총 요청: " << totalRequests << endl;
        cout << "성공: " << successCount << endl;
        cout << "실패: " << errorCount << endl;
    }
};

int main() {
    Statistics stats;
    
    // 요청 처리 스레드
    vector<thread> workers;
    for (int i = 0; i < 10; i++) {
        workers.emplace_back([&]() {
            for (int j = 0; j < 1000; j++) {
                bool success = (rand() % 10) < 9;  // 90% 성공
                stats.recordRequest(success);
            }
        });
    }
    
    // 모니터링 스레드
    thread monitor([&]() {
        for (int i = 0; i < 10; i++) {
            this_thread::sleep_for(chrono::milliseconds(500));
            cout << "성공률: " << stats.getSuccessRate() << "%" << endl;
        }
    });
    
    for (auto& t : workers) {
        t.join();
    }
    monitor.join();
    
    stats.printStats();
}

성능 비교

읽기 중심 워크로드 성능

시나리오mutexshared_mutex성능 향상
읽기 스레드 1개100ms100ms0%
읽기 스레드 4개400ms100ms4배
읽기 스레드 8개800ms100ms8배
읽기 90% / 쓰기 10%500ms150ms3.3배
읽기 50% / 쓰기 50%300ms320ms-6% (느림)
// mutex: 읽기도 배타적 (느림)
mutex mtx;

void reader() {
    lock_guard<mutex> lock(mtx);  // 한 번에 하나만
    // 읽기
}

// shared_mutex: 읽기는 동시 가능 (빠름)
shared_mutex smtx;

void reader() {
    shared_lock<shared_mutex> lock(smtx);  // 여러 스레드 동시
    // 읽기
}

성능 특성 다이어그램

graph LR
    A[Workload Analysis] --> B{Read Ratio}
    
    B -->|90%+| C[shared_mutex]
    C --> D[High Perf Gain]
    
    B -->|70-90%| E[shared_mutex]
    E --> F[Medium Gain]
    
    B -->|<50%| G[mutex]
    G --> H[Low Overhead]
    
    B -->|Write Heavy| I[mutex/atomic]
    I --> J[Simplicity]

자주 발생하는 문제

문제 1: 데드락

// ❌ 락 순서 불일치
void func1() {
    unique_lock<shared_mutex> lock1(mtx1);
    unique_lock<shared_mutex> lock2(mtx2);
}

void func2() {
    unique_lock<shared_mutex> lock2(mtx2);
    unique_lock<shared_mutex> lock1(mtx1);  // 데드락
}

// ✅ 락 순서 일치
void func1() {
    unique_lock<shared_mutex> lock1(mtx1);
    unique_lock<shared_mutex> lock2(mtx2);
}

void func2() {
    unique_lock<shared_mutex> lock1(mtx1);
    unique_lock<shared_mutex> lock2(mtx2);
}

문제 2: 쓰기 기아

// 읽기가 많으면 쓰기가 대기할 수 있음
// 해결: 쓰기 우선 정책 또는 타임아웃

쓰기 기아 시나리오:

sequenceDiagram
    participant R1 as Reader 1
    participant R2 as Reader 2
    participant W as Writer
    participant M as shared_mutex
    
    R1->>M: shared_lock
    R2->>M: shared_lock
    W->>M: unique_lock (wait)
    
    Note over W: waiting...
    
    R1->>M: unlock
    
    Note over W: R2 still reading
    
    R2->>M: unlock
    W->>M: acquire unique_lock
    W->>M: unlock

해결 방법 비교:

방법장점단점구현 난이도
타임아웃데드락 방지실패 처리 필요낮음
쓰기 우선 정책공정성 보장커스텀 구현높음
읽기 제한균형 유지복잡도 증가중간

문제 3: 락 업그레이드

// ❌ shared_lock에서 unique_lock으로 변경 불가
shared_lock<shared_mutex> slock(mtx);
// unique_lock<shared_mutex> ulock(mtx);  // 데드락

// ✅ 락 해제 후 재획득
{
    shared_lock<shared_mutex> slock(mtx);
    // 읽기
}
{
    unique_lock<shared_mutex> ulock(mtx);
    // 쓰기
}

락 업그레이드 문제:

graph TD
    A[Thread: has shared_lock] --> B{Request unique_lock}
    B --> C[Wait for other shared_lock]
    C --> D[Other threads waiting]
    D --> E[❌ Deadlock]
    
    A --> F[Release shared_lock]
    F --> G[Request unique_lock]
    G --> H{Other Thread?}
    H -->|Reading| I[Wait]
    H -->|None| J[✅ Acquire]
    I --> K[Other complete]
    K --> J

FAQ

Q1: shared_mutex는 언제 사용하나요?

A:

  • 읽기가 쓰기보다 훨씬 많을 때
  • 캐시, 설정, 통계

Q2: 성능 향상은?

A: 읽기가 많으면 크게 향상. 쓰기가 많으면 오히려 느릴 수 있음.

Q3: shared_mutex vs mutex?

A:

  • shared_mutex: 읽기 동시 가능
  • mutex: 모두 배타적

Q4: C++14 vs C++17?

A:

  • C++14: shared_timed_mutex
  • C++17: shared_mutex (더 가벼움)

Q5: 락 업그레이드는?

A: 직접 지원 안함. 락 해제 후 재획득.

Q6: shared_mutex 학습 리소스는?

A:

  • “C++ Concurrency in Action”
  • cppreference.com
  • “Effective Modern C++”

관련 글: 뮤텍스·lock_guard, scoped_lock, 데이터 레이스·뮤텍스, 스레드 기초.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ Mutex & Lock | “뮤텍스와 락” 가이드
  • C++ scoped_lock | “범위 락” 가이드
  • C++ Data Race | “Mutex 대신 Atomic을 써야 하는 상황은?” 면접 단골 질문 정리
  • C++ std::thread 입문 | join 누락·디태치 남용 등 자주 하는 실수 3가지와 해결법

관련 글

  • C++ condition_variable 기초 |
  • C++ 멀티스레드 크래시 |
  • C++ 메모리 모델 |
  • C++ 멀티스레딩 |
  • C++ Mutex & Lock |