/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

  Copyright (C) 2003-2020 Uwe Schulzweida, <uwe.schulzweida AT mpimet.mpg.de>
  See COPYING file for copying and redistribution conditions.

  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.
*/

#include <mutex>
#include <condition_variable>

#include "cdo_output.h"

void
Cthread_mutex_lock(const char *caller, std::mutex &p_mutex)
{
  try
    {
      p_mutex.lock();
    }
  catch (const std::system_error &e)
    {
      std::cout << "locking failed in " << caller << ". ErrorCode:" << e.code() << " " << e.what() << std::endl;
    }
}

void
Cthread_mutex_unlock(const char *caller, std::mutex &p_mutex)
{
  try
    {
      p_mutex.unlock();
    }
  catch (const std::system_error &e)
    {
      std::cout << "unlocking failed in " << caller << ". ErrorCode:" << e.code() << " " << e.what() << std::endl;
    }
}

void
Cthread_cond_signal(const char *caller, std::condition_variable &p_cond_var)
{
  Debug(PTHREAD, "+%s (cond = %p)", caller, (void *) &p_cond_var);
  p_cond_var.notify_all();
  Debug(PTHREAD, "-%s (cond = %p)", caller, (void *) &p_cond_var);
}

void
Cthread_cond_wait(const char *caller, std::condition_variable &p_cond, std::unique_lock<std::mutex> &p_locked_mutex)
{
  if (PTHREAD) std::cout << caller << "waiting for condition " << &p_cond << std::endl;

  p_cond.wait(p_locked_mutex);

  if (PTHREAD) std::cout << caller << "finished waiting " << &p_cond << std::endl;
}
