/*!
  \file
  \brief 待機

  \author Satofumi KAMIMURA

  $Id: delay.cpp 1441 2009-10-23 08:49:31Z satofumi $
*/

#include "delay.h"
#include "system_delay.h"
#include "ExecutionType.h"
#include "EventScheduler.h"
#include "Lock.h"

using namespace qrk;


void qrk::delay(int msec)
{
  static EventScheduler event_scheduler;
  static ExecutionType::Type type = ExecutionType::object()->type();

  if (type == ExecutionType::Playback) {
    // デバイス処理で時間を待つので、ここでは待たなくてよい
    return;
  }

  if (type != ExecutionType::Simulation) {
    system_delay(msec);
    return;
  }

  // Simulation 時
  ConditionVariable condition;
  Lock* mutex = event_scheduler.lock();
  if (event_scheduler.registerDelayEvent(&condition, msec)) {
    condition.wait(mutex);
    mutex->unlock();
    return;
  }
  mutex->unlock();

  // この分岐に入るのは、EventScheduler のスレッドが停止しているとき
  fprintf(stderr, "delay: thread stopped.\n");
  //system_delay(1000);
}
