Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::counting_semaphore: limiting concurrent access

std::counting_semaphore maintains a permit count; acquire consumes a permit, while release returns permits and can unblock a waiter.

Version: C++23

Syntax

template<std::ptrdiff_t LeastMaxValue = /* implementation-defined */>
class counting_semaphore {
public:
    static constexpr std::ptrdiff_t max() noexcept;
    constexpr explicit counting_semaphore(std::ptrdiff_t desired);
    void release(std::ptrdiff_t update = 1);
    void acquire();
    bool try_acquire() noexcept;
};

std::counting_semaphore<LeastMaxValue> from <semaphore> maintains a nonnegative counter. acquire() waits until the counter is positive and atomically decrements it; release(update) atomically adds update and unblocks waiters. A release effect strongly happens before a successful acquisition that observes that effect.

std::counting_semaphore::acquire blocks until it successfully atomically decrements a positive counter. std::counting_semaphore::release atomically increments the counter by update and unblocks waiters, with the precondition 0 <= update <= max() - counter. std::counting_semaphore::max returns the largest supported counter value, at least LeastMaxValue; it does not return the current permit count.

LeastMaxValue must be nonnegative. Construction requires 0 <= desired && desired <= max(), and release requires 0 <= update && update <= max() - counter; exceeding capacity violates a precondition. The object is not copyable, and destruction must not race with threads still using it.

try_acquire() does not block, but it may spuriously return false even when the counter is positive. Timed variants can finish later than their deadline. A semaphore transfers permits; it does not by itself protect arbitrary data like a mutex, so shared-state access still needs a correct synchronization protocol.

Examples

#include <iostream>
#include <semaphore>
#include <thread>

int main() {
    std::counting_semaphore<1> ready{0};
    int value = 0;

    std::jthread worker([&] {
        ready.acquire();
        value = 42;
    });

    ready.release();
    worker.join();
    std::cout << value << '\n';
}

Result

42

std::counting_semaphore → 42

Sources