简体   繁体   中英

Swapping buffers without locks in single producer and multiple consumers

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.

Technically, the actual exchange can be performed by:

  • C++11 atomic functions - eg std::atomic_echange , std::atomic_exchange_explicit
  • inline assembly - eg Intel lock xchg
  • GCC builtin functions - __atomic_exchange or older __sync_lock_test_and_set
  • MSVC functions - InterlockedExchangePointer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM