Search code examples
c++c++11condition-variable

purpose for wait_for function in condition variable - C++11


I am new to condition variables, multi-threading and mutexes and I have a fundamental question regarding it.

Quote from en.cppreference.com on wait_for - "blocks the current thread until the condition variable is woken up or after the specified timeout duration".

Why should the current thread be unblocked after a specified duration of time. The basic purpose of condition variable is to notify whenever a "condition" occurs. Does it not cause a overhead if the thread is woken up, say, every 500ms? Spurious wake ups are also inbuilt as a safety mechanism in case a call to notify does not happen/fails etc.

I am obviously missing something basic here but not sure what it is. Any help is appreciated.


Solution

  • The use case for this is if you want to wait for an event to occur, but not indefinitely.

    Maybe after the timeout expired, you want to notify the user that obtaining the result takes longer than expected. Maybe you want to trigger cancellation of the task providing the result.

    As you have correctly pointed out, this causes additional overhead, so it only makes sense to use this instead of wait if you actually have something reasonable to do to react to an expired timeout.

    Spurious wakeups are not so much of a safety mechanism as more an unfortunate necessity imposed by certain hardware architectures. In a perfect world (ie. a world where you only ever call the wait functions with a predicate), no spurious wakeups occur ever.