Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

C++ std::counting_semaphore (C++20)

Reference for std::counting_semaphore and std::binary_semaphore (C++20): acquire, release, try_acquire and limiting concurrent access to a resource.

A semaphore (header <semaphore>, C++20) is a counter that controls access to a limited resource. acquire() decrements the counter, blocking while it is zero. release() increments it, which may wake a waiting thread. Unlike a mutex, a semaphore has no owner: one thread may acquire and a different thread may release, which makes it good for signaling and for limiting how many threads may do something at once.

std::counting_semaphore<Max> allows counts up to Max (a compile-time upper bound, default maximum is implementation-defined and at least 256 by std::counting_semaphore<>). std::binary_semaphore is the alias counting_semaphore<1>.

C++
std::counting_semaphore<4> slots(2);   // at most 2 holders at once
slots.acquire();
// ... use the resource ...
slots.release();

Try it

C++ At most two threads inside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Signaling with a binary semaphore

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
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);
    counting_semaphore(const counting_semaphore&) = delete;

    void release(std::ptrdiff_t update = 1);
    void acquire();
    bool try_acquire() noexcept;
    template<class Rep, class Period>
    bool try_acquire_for(const std::chrono::duration<Rep, Period>& rel_time);
    template<class Clock, class Duration>
    bool try_acquire_until(const std::chrono::time_point<Clock, Duration>& abs_time);
};

using binary_semaphore = std::counting_semaphore<1>;
Name Description
desired The initial counter value. Must be between 0 and max().
release(n) Adds n to the counter and wakes up to n waiters.
acquire() Waits until the counter is positive, then decrements it.
try_acquire() Decrements and returns true if positive; otherwise returns false immediately (may fail spuriously).
try_acquire_for/_until Same, waiting up to a duration or a deadline.

Returns: the try_ functions return bool. Errors / undefined behavior: release that would push the counter above max() is undefined; constructing with a value outside 0..max() is undefined.

Usage notes

  • No ownership. A semaphore does not check who releases it, so unlike std::mutex it cannot protect data by itself; it limits or signals.
  • Semaphore vs mutex: a mutex has one owner and gives mutual exclusion; a semaphore with count N lets N threads in and can be released from another thread.
  • Semaphore vs condition variable: a semaphore remembers signals (the count), so a release before the acquire is not lost.
  • binary_semaphore as a one-shot signal is a lightweight alternative to a promise/future pair for a thread-to-thread handshake.
  • Fairness is not guaranteed. Waiting threads may be woken in any order.
  • Keep acquire/release balanced. Wrap them in a small RAII class if exceptions are possible, since there is no built-in lock guard for semaphores.
  • Bound LeastMaxValue to what you need; small maximums can use faster platform primitives.
  • Header available with -std=c++20 or newer in libstdc++ 11 and later.