/* Network-Integrated Multimedia Middleware (NMM)
 * http://www.motama.com/nmm.html
 *  
 * Copyright (C) 2006-2007
 * Motama GmbH, Saarbruecken, Germany
 * http://www.motama.com
 *  
 * This file is part of NMM. 
 * 
 * NMM is free software; you can redistribute it and/or modify it    
 * under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; only version 2 of the License.      
 * 
 * NMM is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 
 * License for more details.  
 * 
 * You should have received a copy of the GNU General Public License 
 * along with NMM; if not, write to the Free Software Foundation,    
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */


#ifndef NMM_MUTEX_GUARD_HPP
#define NMM_MUTEX_GUARD_HPP

#include "nmm/nmm_prefix.hpp"

#include "ThreadMutex.hpp"

namespace NMM{
  /** This class can be used to ensure that a locked mutex is unlocked if
   * an instance of this class is destroyed
   */
  class MutexGuard {
  public:
    /** Constructor
     * Locks the mutex
     */
    MutexGuard(const ThreadMutex& mutex) : mutex(mutex) { is_owner = false; lock(); }

    /** Destructor
     * Unlocks the Mutex, if it was not unlocked before
     */
    ~MutexGuard() {mutex.unlock();}

    /** This method unlocks the Mutex, if this MutexGuard is the owner
      */
    void unlock()     const  { if (is_owner) { mutex.unlock(); is_owner = false; } }

    /** This method locks the mutex and sets.
      */
    void lock()       const  { is_owner = true; mutex.lock(); }
  private:
    const ThreadMutex& mutex;
    mutable bool is_owner;
  };

}//end namespace NMM

#include "nmm/nmm_suffix.hpp"

#endif

