Domanda

I have two threads, one for data acquisition and the other one for display. In order to avoid from unnecessary synchronization. I use double buffering (or page flipping) as following:

  1. data thread is writing buffer 1 while display thread reading the buffer 2
  2. once writing is done for a buffer, data thread switches to the other buffer (buffer 2) and starts writing new page.
  3. For reading, if a buffer is in the middle of writing, display thread reads from the other buffer.

It actually works well but sometimes (1 per 100 frames) I can see tearing in the display which means there is still race condition.

So how can I implement minimal (effective) synchronization of this double buffering? A pseudo algorithm would be enough for me.

È stato utile?

Soluzione

You can do this with two semaphores. It is a variation of the Producer/Consumer problem. Pseudo-code in the link I provided.

Altri suggerimenti

What language, platform and (if necessary) Graphics API are you working with?

A pseudo algorithm would be enough for me.

There is such a variety in approaches depending on the situation, you really should be more specific. For instance, you can declare critical sections so that thread 1 waits when writing while thread 2 is reading, and so on - but there are reasons not to do that.

You could just work with message passing, which would wake up the drawing thread rather than working with critical sections. So it really depends a great deal on language, platform and graphics API.

Here's some code that uses message passing to synchronize the rendering and transfer to graphics:

DataAcquisitionThread.Run() {
  ProcessData();
  Wait(message);
  DrawToBackBuffer();
}

DisplayThread.Run() {
  Wait(message);
  SwapBuffer(message.bufferNumber);
  Render(buffer);
  SendMessage(message.defaultMessage());
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top