66#include < mutex>
77#include < shared_mutex>
88
9- #if 0 // Use real mutex for write buffer, not needed with a single writer
9+ #if 0 // Use a real mutex for the write buffer; not needed with a single writer.
1010using WriteMutex = std::mutex;
1111#else
1212class FakeMutex {
@@ -26,52 +26,52 @@ class DoubleBuffer {
2626 using read_lock = std::shared_lock<std::shared_mutex>;
2727 using write_lock = std::unique_lock<WriteMutex>;
2828
29- // Returns a const reference to the current read buffer along with a shared read lock
29+ // Returns a const reference to the current read buffer along with a shared read lock.
3030 std::pair<const T&, read_lock> readBuffer () const
3131 {
3232 read_lock lock (readMutex_);
3333 return { buffer_[index_], std::move (lock) };
3434 }
3535
36- // Returns a reference to the current write buffer along with an exclusive write lock
36+ // Returns a reference to the current write buffer along with an exclusive write lock.
3737 std::pair<T&, write_lock> writeBuffer ()
3838 {
3939 write_lock lock (writeMutex_);
4040 return { buffer_[1 - index_], std::move (lock) };
4141 }
4242
43- // Clones the current read buffer
43+ // Clones the current read buffer.
4444 T clone () const
4545 {
4646 read_lock lock (readMutex_);
4747 return buffer_[index_];
4848 }
4949
50- // Sets new data to the write buffer and swaps the buffers
50+ // Sets new data in the write buffer and swaps the buffers.
5151 void setAndSwap (T newData)
5252 {
5353 write_lock writeLock (writeMutex_);
5454 buffer_[1 - index_] = std::move (newData);
5555 swap (std::move (writeLock));
5656 }
5757
58- // Swaps the read and write buffers
58+ // Swaps the read and write buffers.
5959 void swap ()
6060 {
6161 write_lock writeLock (writeMutex_);
6262 swap (std::move (writeLock));
6363 }
6464
65- // Swaps the read and write buffers using an existing write lock
65+ // Swaps the read and write buffers using an existing write lock.
6666 void swap (write_lock&& writeLock)
6767 {
68- std::unique_lock<std::shared_mutex> readLock (readMutex_); // exclusive lock to prevent reads during swap
68+ std::unique_lock<std::shared_mutex> readLock (readMutex_); // Exclusive read lock to prevent reads during the swap.
6969 index_ = 1 - index_;
7070 }
7171
7272private:
7373 T buffer_[2 ];
74- int index_ = 0 ; // read index (alternates between 0 and 1)
74+ int index_ = 0 ; // Read index (alternates between 0 and 1).
7575 WriteMutex writeMutex_;
7676 mutable std::shared_mutex readMutex_;
7777};
0 commit comments