counting_semaphore — std::counting_semaphore

counting_semaphore — std::counting_semaphore

std::counting_semaphore리소스의 개수를 세는 가벼운 동기화 기본 요소예요. C++20에서 도입됐어요. <semaphore> 헤더에 있어요.

binary_semaphore는 카운트 최대값이 1인 특수화예요.

출처: cppreference

본문

// <semaphore> 헤더, C++20
template< std::ptrdiff_t LeastMaxValue = /* implementation-defined */ >
class counting_semaphore;                    // (1)

using binary_semaphore = std::counting_semaphore<1>;   // (2)
  • (1) counting_semaphore — 가벼운 동기화 원시 요소
  • (2) binary_semaphore — 카운트가 0/1인 세마포어

사용 예 — 제한된 리소스

#include <semaphore>
#include <thread>

std::counting_semaphore<3> slots{3};   // 최대 3개 허용

void worker(int id) {
    slots.acquire();    // 슬롯 획득 (없으면 대기)
    // 리소스 사용
    slots.release();    // 슬롯 반납
}

주요 연산

연산 설명
acquire() 카운트를 1 줄이고, 0이면 진행 불가 (대기)
release(n) 카운트를 n만큼 증가
try_acquire() 즉시 시도 (실패 시 false)
try_acquire_for(dur) 시간 제한 시도
try_acquire_until(tp) 시각 제한 시도
max() 최대 카운트
// try_acquire — 블로킹 없이 시도
if (sem.try_acquire()) {
    // 성공
} else {
    // 리소스 없음
}

binary_semaphore

// 신호(깨우기) 동기화
std::binary_semaphore signal{0};

// worker가 끝나면 신호
signal.release();
// 다른 스레드는 신호를 기다림
signal.acquire();

특징

  • 가볍고, OS 세마포어에 비해 이식성 있는 추상화를 제공해요.
  • counting_semaphore는 최대값이 템플릿 인자로 정해져요.
  • 병렬 알고리즘의 슬롯 제한, 태스크 큐 크기 제어 등에 유용해요.

std::counting_semaphore는 N개의 동시 실행을 제한하거나 스레드 간 신호를 보낼 때의 표준적이고 가벼운 방법이에요.

더 알아보기 (Learn more)

cppreference