jeudi 11 avril 2019

How to test condition variable in C++?

I have a pretty basic method that calls wait() on a condition variable (from <condition_variable> in C++.

void WaitForEvent() {
  std::unique_lock<std::mutex> lock(mutex_);
  while (!event_counter_) {
    cond_var_.wait(lock);
  } 
  return;
}

Now I want to unit test that method's interaction. So I want to call WaitForEvent, then call PostEvent which will notify the condition variable and check if the wait has stopped.

void PostEvent() {
  // ...
  cond_var_.notify_all();
}

How'd I best do that in a unit test?

The only solution I've come up with so far is

  1. start a thread that calls WaitForEvent
  2. make the thread set a flag after the WaitForEvent call
  3. call PostEvent in the main thread
  4. wait for x seconds in the main thread
  5. check if the flag has been set

However, I don't like the fact that I can't join the thread here. If I join,then my tests will block if WaitForEvent doesn't unblock as expected. Also, I don't like adding delays in unit tests.

Is there any better solution to my problem? Thanks in advance :)

Aucun commentaire:

Enregistrer un commentaire