Table of Contents

<semaphore>

<semaphore> provides std::binary_semaphore (0 or 1, like a lock) and std::counting_semaphore<N> (up to N resources available). Threads call acquire() to decrement the count (blocking if zero) and release() to increment.

Use semaphores for limiting access to a fixed pool of resources.

Example

This example limits concurrent access to a resource pool using a counting semaphore, where three threads compete for two available slots.

// compile: g++ -std=c++20 -pthread -o semaphoreexample semaphoreexample.cpp
// run: ./semaphoreexample
// description: limit concurrent access with counting_semaphore
 
#include <semaphore>
#include <thread>
#include <iostream>
 
std::counting_semaphore<2> resources(2);
 
void use_resource(int id) {
    resources.acquire();
    std::cout << "thread " << id << " using resource\n";
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    resources.release();
}
 
int main() {
    std::thread t1(use_resource, 1);
    std::thread t2(use_resource, 2);
    std::thread t3(use_resource, 3);
 
    t1.join();
    t2.join();
    t3.join();
 
    return 0;
}