Barry
Barry

Reputation: 304122

condition_variable::wait_for always waits?

I have some code in a unit test that waits until my vector is sufficiently big:

bool waitForOutwardMessages(size_t size, int millis) {
    std::unique_lock<std::mutex> lock(mutex);
    return ready.wait_for(lock, std::chrono::milliseconds(millis), [=]{
        return this->messages.size() >= size;
    });
}

std::mutex mutex;
std::condition_variable ready;

Easy enough. Except when I run this test, I'm expecting that the the vector in question should fill up on the order of milliseconds after I make this call on the other thread. Maybe 10ms, maybe 100ms, certainly within 1s. But when I pass in 5000 as the millis argument, this function always waits 5 seconds.

On the one hand, this is fine, because I don't care how long this test takes anyway. On the other hand, I thought it was supposed to wait up to the duration only if the condition variable wasn't notified... not always?

Is there a way to get this to return earlier?

Upvotes: 1

Views: 1298

Answers (1)

Jesus Ramos
Jesus Ramos

Reputation: 23266

Check that you are actually calling signal or broadcast on ready. There's a possible race if you're not careful where you can signal the condition before you actually wait on it (which will cause a wait until timeout).

Upvotes: 1

Related Questions