0

We have use case where data will be updated at regular intervals. But there will be multiple thread reading the data. So the solution which we are thinking is to use double buffers. So the consumer threads will be reading a foreground page while the producer will update the background page. Once producer updates the background page it will swap the foreground page with this page without taking lock. As the data will be same or different we still don't care as it will not impact the operation. Now the question is how to do the job as I know the traditional producer consumer problem where I can use two buffer for the same job and keep rotating the things but the issue to swap I would need to have a lock but that is what we want to avoid.

So how to perform the things. Any pointer in this regard will be great.

Abhinav
  • 975
  • 4
  • 18
  • 35
  • 1
    How do you synchronize the producers and consumers? What happens with consumers reading the foreground page when the producer decides to swap and start writing to that very same page ? – chill Nov 30 '12 at 13:25
  • We are not worried about synchronizing producer and consumer as the foreground and background data will be almost same. As we are going to use index so there could be the case where some consumer will read older page and some consumer will read new page but later all consumer will read common data. Only thing is we are looking that we don't want a lock while swapping the data. So it sought of lock free switching of buffers. – Abhinav Nov 30 '12 at 15:29

1 Answers1

1

Technically, the actual exchange can be performed by:

  • C++11 atomic functions - e.g std::atomic_echange, std::atomic_exchange_explicit
  • inline assembly - e.g. Intel lock xchg
  • GCC builtin functions - __atomic_exchange or older __sync_lock_test_and_set
  • MSVC functions - InterlockedExchangePointer
chill
  • 16,470
  • 2
  • 40
  • 44