//
// This is a class for guard objects using OpenMP
// It is adapted from the book
// "Pattern-Oriented Software Architecture". 
// Taken from http://www.thinkingparallel.com - Michael Suess
//
// This file is part of MorphoGraphX - http://www.MorphoGraphX.org
// Copyright (C) 2012-2015 Richard S. Smith and collaborators.
//
// If you use MorphoGraphX in your work, please cite:
//   http://dx.doi.org/10.7554/eLife.05864
//
// MorphoGraphX is free software, and is licensed under under the terms of the 
// GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
//
#include <OMPGuard.hpp>

namespace mgx
{ 
  /** Construct guard object and acquire our lock */
  OMPGuard::OMPGuard(omp_lock_t &lock) : _lock (&lock), _owner(false)
  {
    acquire ();
  }
   
  /** 
   * Explicitly set our lock 
   */
  void OMPGuard::acquire()
  {
    omp_set_lock(_lock);
    _owner = true;
  }
   
  /** 
   * Explicitly unset our lock.
   * Only unset it, though, if we are still the owner.
   */
  void OMPGuard::release()
  {
    if(_owner) {
      _owner = false;
      omp_unset_lock(_lock);
    }
  }
   
  /** 
   * Destruct guard object, release the lock 
   */
  OMPGuard::~OMPGuard()
  {
    release();
  }
}
