Search code examples
multithreadingdouble-buffering

how to synchronize double buffering in multithreaded app


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.


Solution

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