title: Multithreaded double buffer
body: <p>I have a <code>Buffer</code> class that implements the <a href="https://en.wikipedia.org/wiki/Multiple_buffering#Double_buffering_in_computer_graphics" rel="nofollow noreferrer">double buffer pattern</a> designed with multithreading in mind:</p>
  
  <pre><code>class Buffer {
  public:
     void write(size_t idx, float value) {
        std::lock_guard&lt;std::mutex&gt; lk(mut);
        (*next)[idx] = value; // write to next buffer
     }
  
     float read(size_t idx) const {
        std::lock_guard&lt;std::mutex&gt; lk(mut);
        return (*current)[idx]; // read from current buffer
     }
  
     void swap() noexcept {
        std::lock_guard&lt;std::mutex&gt; lk(mut);
        std::swap(current, next); // swap pointers
     }
  
     Buffer() : buf0(32), buf1(32), current(&amp;buf0), next(&amp;buf1) { }
  private:
     std::vector&lt;float&gt; buf0, buf1; // two buffers
     std::vector&lt;float&gt; *current, *next;
     mutable std::mutex mut;
  };
  </code></pre>
  
  <p>This class contains two buffers. The buffers are always accessed through pointers:</p>
  
  <ul>
  <li>A buffer where reading from, specified by <code>current</code> pointer.</li>
  <li>A buffer where writing to, specified by <code>next</code> pointer.</li>
  </ul>
  
  <p>There will be two threads: an updating thread will write to the next buffer calling the <code>write</code> method, a reading thread will read from the current buffer calling the <code>read</code> method. When the updating thread is done it calls <code>swap</code> to swap the pointers to the buffers.</p>
  
  <p><strong>The swapping of the buffers must be done atomically</strong> so I have to lock the mutex in every method (creating the <code>lk</code> object).</p>
  
  <p>The problem is that locking the mutex in every method prevents the two threads from accessing their corresponding buffer at the same time. But the two buffers are independent: there is no problem if one thread modifies one buffer while the other thread reads the other buffer. </p>
  
  <p>I want to allow the updating thread to modify its buffer at the same time the reading thread reads its corresponding buffer. Any way to achieve this?</p>