title: Ensure that a thread doesn't lock a mutex twice?
body: <p>Say I have a thread running a member method like <code>runController</code> in the example below:</p>
  
  <pre><code>class SomeClass {
  public:
      SomeClass() { 
           // Start controller thread
           mControllerThread = std::thread(&amp;SomeClass::runController, this) 
      }
  
      ~SomeClass() {
           // Stop controller thread
           mIsControllerThreadInterrupted = true;
           // wait for thread to die.
           std::unique_lock&lt;std:::mutex&gt; lk(mControllerThreadAlive); 
      }
  
      // Both controller and external client threads might call this
      void modifyObject() {
           std::unique_lock&lt;std::mutex&gt; lock(mObjectMutex);
           mObject.doSomeModification();
      }
      //...
  private:
      std::mutex mObjectMutex;
      Object mObject;
  
      std::thread mControllerThread;
      std::atomic&lt;bool&gt; mIsControllerInterrupted;
      std::mutex mControllerThreadAlive;
  
      void runController() {        
          std::unique_lock&lt;std::mutex&gt; aliveLock(mControllerThreadAlive);
          while(!mIsControllerInterruped) {
              // Say I need to synchronize on mObject for all of these calls
              std::unique_lock&lt;std::mutex&gt; lock(mObjectMutex);
              someMethodA();
              modifyObject(); // but calling modifyObject will then lock mutex twice
              someMethodC();
          }
      }
      //...
  };
  </code></pre>
  
  <p>And some (or all) of the subroutines in <code>runController</code> need to modify data that is shared between threads and guarded by a mutex. Some (or all) of them, might also be called by other threads that need to modify this shared data. </p>
  
  <p>With all the glory of C++11 at my disposal, how can I ensure that no thread ever locks a mutex twice?</p>
  
  <p>Right now, I'm passing <code>unique_lock</code> references into the methods as parameters as below. But this seems clunky, difficult to maintain, potentially disastrous, etc...</p>
  
  <pre><code>void modifyObject(std::unique_lock&lt;std::mutex&gt;&amp; objectLock) {
  
      // We don't even know if this lock manages the right mutex... 
      // so let's waste some time checking that.
      if(objectLock.mutex() != &amp;mObjectMutex)
           throw std::logic_error();
  
      // Lock mutex if not locked by this thread
      bool wasObjectLockOwned = objectLock.owns_lock();
      if(!wasObjectLockOwned)
          objectLock.lock();
  
      mObject.doSomeModification();
  
      // restore previous lock state
      if(!wasObjectLockOwned)
          objectLock.unlock();
  
  }
  </code></pre>
  
  <p>Thanks!</p>