Semaphore class in action

suggest change

The following function starts four threads. The semaphore’s initial count is one. s2 calls wait immediately and consumes that count. s1 and s3 sleep before waiting. s4 sleeps, then calls notify, which increments the count and does notify_one(). wait blocks on the condition variable. It does not spin. The loops never finish, so the join() calls do not return. The snippet uses std names unqualified.

int main()
{
    Semaphore sem(1);
    
    thread s1([&]() {
        while(true) {
            this_thread::sleep_for(std::chrono::seconds(5));
            sem.wait( 1 );
        }           
    });
    thread s2([&]() {
        while(true){
            sem.wait( 2 );
        }
    });
    thread s3([&]() {
        while(true) {
            this_thread::sleep_for(std::chrono::milliseconds(600));
            sem.wait( 3 );
        }
    });
    thread s4([&]() {
        while(true) {
            this_thread::sleep_for(std::chrono::seconds(5));
            sem.notify( 4 );
        }
    });
    
    
    s1.join();
    s2.join();
    s3.join();
    s4.join();

    ...
    }

Feedback about page:

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



Table Of Contents