Appendix 3.7: Timer.c
/* Timer.c */
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <synch.h>
#include <thread.h>
#include <Timer.h>
/*================================================*/
/* Routines for implementing a simple tick timer. */
/*================================================*/
int WaitFactor = 0; /* The number of ticks to wait. */
long long StartTime; /* NanoTime at start of piece. */
long long NanoInterval; /* Nano-second value of the interval. */
/**************************************************************************/
/* Sets the nanosecond interval per tick required for a particular tempo .*/
/**************************************************************************/
long long
SetInterval(int BeatsPerMinute)
{
/* Calculate the interval value. */
const nano = 1000000000.0;
double interval = 60.0 / ((double) TICKSPERBEAT * (double) BeatsPerMinute);
return (NanoInterval = (long long) (interval * nano));
}
/**********************************/
/* Set a delay value to wait for. */
/**********************************/
void
SetDelay(int pause)
{
WaitFactor = pause;
}
/**********************/
/* Has a tick passed? */
/**********************/
int
TickPassed()
{
long long TimeDiff = gethrtime() - StartTime;
if (TimeDiff >= NanoInterval) {
StartTime += NanoInterval;
return(1);
} else
return(0);
}
/********************************************************/
/* Wait for a tick and return the number of ticks left. */
/********************************************************/
int
Delay()
{
if (WaitFactor > 0 && TickPassed())
WaitFactor--;
return(WaitFactor);
}
/********************/
/* Intialise timer. */
/********************/
long long
InitTimer(int Tempo)
{
long long interval = SetInterval(Tempo);
StartTime = gethrtime();
return(interval);
}
/******************************************************************/
/* Reset the time and return the number of ticks that we removed. */
/******************************************************************/
int
ResetTime()
{
int tick = 0;
/* Remove all pending semaphores. */
while(TickPassed()) tick += 1;
return(tick);
}
/*********************************************************************/
/* Allow a process to post time, adding it to the pool of time to be */
/* to be collected later. */
/*********************************************************************/
void
PostTime(int delta)
{
StartTime -= NanoInterval * delta;
}