title: How would you implement your own reader/writer lock in C++11?
body: <p>I have a set of data structures I need to protect with a readers/writer lock. I am aware of boost::shared_lock, but I would like to have a custom implementation using std::mutex, std::condition_variable and/or std::atomic so that I can better understand how it works (and tweak it later). </p>
  
  <p>Each data structure (moveable, but not copyable) will inherit from a class called Commons which encapsulates the locking. I'd like the public interface to look something like this:</p>
  
  <pre><code>class Commons {
  public:
      void read_lock();
      bool try_read_lock();
      void read_unlock();
  
      void write_lock();
      bool try_write_lock();
      void write_unlock();
  };
  </code></pre>
  
  <p>...so that it can be publicly inherited by some:</p>
  
  <pre><code>class DataStructure : public Commons {};
  </code></pre>
  
  <p>I'm writing scientific code and can generally avoid data races; this lock is mostly a safeguard against the mistakes I'll probably make later. Thus my priority is low read overhead so I don't hamper a correctly-running program too much. Each thread will probably run on its own CPU core. </p>
  
  <p>Could you please show me (pseudocode is ok) a readers/writer lock? What I have now is supposed to be the variant that prevents writer starvation. My main problem so far has been the gap in read_lock between checking if a read is safe to actually incrementing a reader count, after which write_lock knows to wait. </p>
  
  <pre><code>void Commons::write_lock() {
      write_mutex.lock();
      reading_mode.store(false);
      while(readers.load() &gt; 0) {}
  }
  
  void Commons::try_read_lock() {
      if(reading_mode.load()) {
          //if another thread calls write_lock here, bad things can happen
          ++readers; 
          return true;
      } else return false;
  }
  </code></pre>
  
  <p>I'm kind of new to multithreading, and I'd really like to understand it. Thanks in advance for your help!</p>