Semaphore

suggest change

Introduction

The C++20 standard library provides std::counting_semaphore and std::binary_semaphore in <semaphore>. A semaphore maintains a counter: acquire() waits until it can decrement the counter, and release() increments it and may wake a waiting thread.

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

std::binary_semaphore ready{0};

int main()
{
    std::jthread worker([] {
        ready.acquire();
        std::cout << "worker started\n";
    });

    ready.release();
}
worker started

For code limited to older language versions, the same abstraction can be built from std::mutex and std::condition_variable, but the implementation must handle wakeups and counter updates while holding the mutex.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents