In case of std::counting_semaphore, what will happened if one thread made counter value zero and other thread again came and found acquire()

Viewed 45

As you can see in below example Thread t1 has made counter value to zero but Thread t2 now trying to decrement that value again. What will happened in below case because I am seeing processing time exceeded always.could anyone suggest any online compiler i can use for testing such examples?

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

std::vector<int> myVec{};
std::counting_semaphore<2> signal(1);

void addElement() 
{
    std::cout << "In addElement() \n";
    myVec.insert(myVec.end(), {0, 1, 0, 3});
    std::cout << "Sender: Element added ."  << '\n';
    std::cout << "In addElement() value1 :" << signal.max() << "\n";
    signal.release();    
}

void accessElement() 
{
    std::cout << "Waiter:: Waiting for data accessing." << '\n';
    std::cout << "In accessElement() value1 :" << signal.max() << "\n";
    signal.acquire();
    std::cout << "updated the element........." << '\n';
}

int main() 
{
    std::thread t1(accessElement);
    t1.join();
    std::thread t3(accessElement);
    t3.join();
    std::thread t2(addElement);
    t2.join();
}
1 Answers

Why do you create these threads?

    std::thread t1(accessElement);
    t1.join();
    std::thread t3(accessElement);
    t3.join();
    std::thread t2(addElement);
    t2.join();

Why don't you simply do this instead?

    accessElement();
    accessElement();
    addElement();

It never makes sense to join() a new thread in the very next statement after the statement that creates the thread. The whole point of threads is to allow the the new thread to do one thing while the caller proceeds to do some other thing at the same time.

    std::thread t1(doOneThing);
    doSomeOtherThingAtTheSameTime();
    t1.join();
    // Can't get here until both things have been done.
Related