본문으로 건너뛰기
Previous
Next
C++ shared_mutex | '읽기-쓰기 락' 가이드

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;
    }
};

락 동작 다이어그램

다음은 mermaid 예제 코드입니다.

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쓰기❌ 배타적❌ 블로킹❌ 블로킹

C/C++ 예제 코드입니다.

// shared_lock: 읽기 (여러 스레드 동시 가능)
shared_lock<shared_mutex> slock(mtx);

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

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

동시 접근 시나리오

다음은 mermaid 예제 코드입니다.

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% (느림)

reader 함수의 구현 예제입니다.

// mutex: 읽기도 배타적 (느림)
mutex mtx;

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

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

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

성능 특성 다이어그램

다음은 mermaid 예제 코드입니다.

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: 데드락

func1 함수의 구현 예제입니다.

// ❌ 락 순서 불일치
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: 쓰기 기아

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

쓰기 기아 시나리오:

다음은 mermaid 예제 코드입니다.

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: 락 업그레이드

C/C++ 예제 코드입니다.

// ❌ 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);
    // 쓰기
}

락 업그레이드 문제:

다음은 mermaid 예제 코드입니다.

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++ shared_mutex | ‘읽기-쓰기 락’ 가이드」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ shared_mutex | ‘읽기-쓰기 락’ 가이드」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, shared_mutex, mutex, threading, 등으로 검색하시면 이 글이 도움이 됩니다.