简体   繁体   中英

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM