0

I have a C++ program with a test class with two methods:

void IntegrationTestBase::wait_test_end() {
    unique_lock<mutex> lock(m_mutex);

    m_cond.wait(lock);
}

void IntegrationTestBase::notify_test_end() {
    XN_LOGF_ITEST_BASE(INFO, "Test end");

    m_cond.notify_all();

m_cond is a conditional variable, m_mutex is mutex.

The flow is that an unknow number of threads might wait_test_end and then some other thread might notify_test_end and they will all stop waiting.

The problem is that after notify_test_end some other threads might wait_test_end and they will be stuck in the wait indefinitly.

How can I cope with this?

Hexaholic
  • 3,299
  • 7
  • 30
  • 39
Epic
  • 572
  • 2
  • 18
  • I found [this post](http://stackoverflow.com/q/21757124/1460794) useful when looking for a good example. – wally Mar 16 '16 at 13:38

1 Answers1

1

The way to cope with it is understand what condition variable is and what it is not. In particular, it is not a singalling mechanism.

Condition variable protect a certain resource (a real variable, for example). The pattern of using it is always the same:

  1. Lock the mutex
  2. Check the real variable to see if it contains the value you are interested in
  3. If not, wait on condition variable - if yes, use the variable and unlock the mutex.
SergeyA
  • 61,605
  • 5
  • 78
  • 137