I have a triple buffer implementation that is often used in threads in such a way that when new data is expected, there's always a WaitData(n) function called on the buffer (A condition variable's timed_wait(n) function is called) and afterwards a HasNewData() is called on the buffer. If both return true, the buffer can be read.

When the buffer is successfully written to, the notify_all() of the condition variable notifies all the waiting functions.

Now I'm wondering, why do I have to do the waiting for the condition variable? Can't I just periodically poll the HasNewData() of the triple buffer?

Both seem to have the same purpose to me! Only with the WaitData() function my thread is stalling fo n seconds.

Here is a code example of a reading and a writing thread

  if(buffer.WaitData(3) && buffer.IsData())
   data = buffer.GetRead();

  data = buffer.GetWrite();
  data = FillBuffer();
  • 1
    Does your code use a specific library or buffering implementation? – user22815 Aug 13 '15 at 13:34

The whole point of condition variables is that you can suspend a thread until some (for that thread) external event occurs.

The advantage of suspending a thread over letting it run continuously and check if it can continue is that a suspended thread does not needlessly consume CPU time and allows the processor to be used to perform useful tasks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.