Example #1
0
void CTestSemaphoreApp::Consume(int Num)
{
    for (int i = Num; i > 0; --i ) {
        // we can only consume one by one
        s_semContent.Wait();
        s_semStorage.Wait();
        --s_Counter;
        NcbiCout << "-1=" << s_Counter << NcbiEndl;
        s_semStorage.Post();
        SleepMilliSec(500);
    }
}
Example #2
0
void CTestSemaphoreApp::Produce(int Num)
{
    // Storage semaphore acts as a kind of mutex - its only purpose
    // is to protect Counter
    s_semStorage.Wait();
    s_Counter += Num;
    NcbiCout << "+" << Num << "=" << s_Counter << NcbiEndl;
    s_semStorage.Post();

    // Content semaphore notifies consumer threads of how many items can be
    // consumed. Slow consumption with fast production causes Content semaphore
    // to overflow from time to time. We catch exception and wait for consumers
    // to consume something
    for (bool Posted=false; !Posted;) {
        try {
            s_semContent.Post(Num);
            Posted = true;
        }
        catch (exception& e) {
            NcbiCout << e.what() << NcbiEndl;
            SleepMilliSec(500);
        }
    }
}