title: readers-/writers multithreading in C++11
body: <p>I'm trying to implement a readers writers solution in C++ with std::thread.</p>
  
  <p>I create several reader-threads that run in an infinite loop, pausing for some time in between each read access. I tried to recreate the algorithm presented in Tanenbaum's book of Operating Systems:</p>
  
  <pre><code>    rc_mtx.lock(); // lock for incrementing readcount
      read_count += 1;
      if (read_count == 1) // if this is the first reader
          db_mtx.lock(); // then make a lock on the database
      rc_mtx.unlock();
  
      cell_value = data_base[cell_number]; // read data from database
      rc_mtx.lock();
      read_count -= 1; // when finished 'sign this reader off'
      if (read_count == 0) // if this was the last one
          db_mtx.unlock(); // release the lock on the database mutex
      rc_mtx.unlock();
  </code></pre>
  
  <p>Of course, the problem is that the thread who might satisfy the condition of being the last reader (and therefore want to do the unlock) has never acquired the <code>db_mtx</code>.
  I tried to open another 'mother' thread for the readers to take care of 
  acquiring and releasing the mutex, but I go lost during the process.
  If there is an elegant way to overcome this issue (thread might try to release a mutex that has never been acquired) in an elegant way I'd love to hear!</p>