2

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

::readThread()
{
  if(buffer.WaitData(3) && buffer.IsData())
  {
   data = buffer.GetRead();
   buffer.Release();
  }
}

::writeThread()
{
  data = buffer.GetWrite();
  data = FillBuffer();
  buffer.Release();
}
gnat
  • 21,442
  • 29
  • 112
  • 288
tzippy
  • 147
  • 1
  • 4
  • 1
    Does your code use a specific library or buffering implementation? –  Aug 13 '15 at 13:34

1 Answers1

3

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.

Bart van Ingen Schenau
  • 71,712
  • 20
  • 110
  • 179