/* 
 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 *
 * This program 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; version 2 of the
 * License.
 * 
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#ifndef _BASE_THREADING_H_
#define _BASE_THREADING_H_

#include "common.h"

#include <glib.h>

namespace base {

//! \brief RAII style GMutex locker/unlocker  
class BASELIBRARY_PUBLIC_FUNC GMutexLock
{
protected:
  GMutex *mutex;
public:
  GMutexLock(GMutex *mtx) : mutex(mtx)
  {
    if (mutex)
      g_mutex_lock(mutex);
  }
  GMutexLock(const GMutexLock &lock)
  {
    GMutexLock *lock_= const_cast<GMutexLock*>(&lock);
    operator=(*lock_);
  }
  ~GMutexLock()
  {
    reset();
  }
  GMutex * release()
  {
    GMutex *res= mutex;
    mutex= NULL;
    return res;
  }
  void reset()
  {
    if (mutex)
    {
      g_mutex_unlock(mutex);
      mutex= NULL;
    }
  }
  GMutexLock & operator=(GMutexLock& lock)
  {
    mutex= lock.release();
    return *this;
  }
};

class BASELIBRARY_PUBLIC_FUNC GMutexTryLock : public GMutexLock
{
public:
  GMutexTryLock(GMutex *mtx) : GMutexLock(0)
  {
    if (!g_mutex_trylock(mtx))
      mutex = NULL;
    else
      mutex = mtx;
  }
  
  bool locked() const
  {
    return mutex != NULL;
  }
};

//! \brief RAII style GStaticMutex locker/unlocker  
class BASELIBRARY_PUBLIC_FUNC GStaticMutexLock // Note: must compile with strict-aliasing disabled (-fno-strict-aliasing in gcc)
{
  GStaticMutex    &mutex;
public:
  GStaticMutexLock(GStaticMutex& mtx);
  ~GStaticMutexLock();
};

class BASELIBRARY_PUBLIC_FUNC GStaticRecMutexLock // Note: must compile with strict-aliasing disabled (-fno-strict-aliasing in gcc)
{
  GStaticRecMutex    &mutex;
public:
  GStaticRecMutexLock(GStaticRecMutex& mtx);
  ~GStaticRecMutexLock();
};

};

#endif