/* 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_THREAD_MUTEX_HPP
#define NMM_THREAD_MUTEX_HPP

#include "nmm/nmm_prefix.hpp"

#include "nmm/Result.hpp"

#include <pthread.h>
#include "visibility.hpp"

namespace NMM{

  class ThreadCondition;

  /** Wrapper for the pthread_mutex variables.
   */
  class DLLEXPORT ThreadMutex {
    /** 
     * Define ThreadCondition as friend. So it can access mutex.
     */
    friend class ThreadCondition;
  public:
    enum MutexKind {FAST, RECURSIVE};

    /** Constructor
     *
     * @param mutex_kind determines whether a ThreadMutex can be
     *        locked again by a thread that already owns it (RECURSIVE) or not (FAST).
     *        Default value is Fast.
     */
    ThreadMutex(MutexKind mutex_kind = FAST);

    /** Destructor
     */
    ~ThreadMutex();

    /** This method locks the mutex. If the mutex is currently unlocked, it becomes locked
     * and  owned  by  the calling  thread. If the mutex is already locked by
     * another thread, the mutex suspends the calling thread until the mutex is unlocked.
     * If the MutexKind is 'Recursive' and the current thread locks again, a counter
     * is increased.
     */	
    void lock()      const;

    /** This method unlocks the mutex. If the MutexKind 'Fast', unlock
     * releases the mutex. If MutexKind is 'Recursive', it
     * decrements the locking  count  of  the  mutex and only when this
     * count reaches zero the mutex is released.
     */
    void unlock()    const;

    /** Tries to lock a mutex. This method differs form lock, that this method returns imediatly.
     * 
     * @return FAILURE if the mutex is already locked by another thread and can not be locked else SUCCESS
     */
    Result tryLock() const;

  private:
    /** Disabled Copy Constructor
     */
    ThreadMutex(const ThreadMutex&);    

    /** Disabled assignement operator
     */
    void operator=(const ThreadMutex&); 

    mutable pthread_mutex_t mutex;
  };

}//end namespace NMM

#include "nmm/nmm_suffix.hpp"

#endif

