/*
-This file is part of libmspframework
+This file is part of libmspcore
Copyright © 2006 Mikko Rasa, Mikkosoft Productions
Distributed under the LGPL
*/
+
#include "timer.h"
#include "utils.h"
namespace Msp {
namespace Time {
-Timer::Timer(const Time::TimeDelta &d):
- interval(d),
- timeout(now()+d)
-{
- MutexLock l(set_mutex);
- timers.insert(this);
- thread.nudge();
-}
+Timer::Timer():
+ slots(slot_compare)
+{ }
Timer::~Timer()
{
- MutexLock l(set_mutex);
- timers.erase(this);
- thread.nudge();
+ while(!slots.empty())
+ {
+ delete slots.top();
+ slots.pop();
+ }
}
-Timer::ThreadProxy Timer::thread;
-Mutex Timer::set_mutex;
-set<Timer *> Timer::timers;
-
-Timer::Thread::Thread():
- done(false)
+Timer::Slot &Timer::add(const TimeDelta &td)
{
- launch();
+ Slot *s=new Slot(td);
+ mutex.lock();
+ slots.push(s);
+ mutex.unlock();
+ sem.signal();
+ return *s;
}
-/**
-Notifies the thread that a change in the timers occurred.
-*/
-void Timer::Thread::nudge()
+Timer::Slot &Timer::add(const TimeStamp &ts)
{
+ Slot *s=new Slot(ts);
+ mutex.lock();
+ slots.push(s);
+ mutex.unlock();
sem.signal();
+ return *s;
}
-/**
-Tells the thread to finish and terminate gracefully. This function will return
-after the thread has terminated.
-*/
-void Timer::Thread::finish()
+void Timer::tick(bool block)
{
- if(!done)
+ if(slots.empty())
{
- done=true;
- sem.signal();
+ if(block)
+ sem.wait();
+ return;
}
- join();
-}
+ mutex.lock();
+ Slot *next=slots.top();
+ mutex.unlock();
-void Timer::Thread::main()
-{
- while(!done)
+ const TimeStamp &stamp=next->get_timeout();
+ const TimeStamp t=now();
+ if(stamp<=t || (block && sem.wait(stamp-t)==1))
{
- set_mutex.lock();
- Timer *next=0;
- TimeStamp next_ts;
- for(set<Timer *>::iterator i=timers.begin(); i!=timers.end(); ++i)
- {
- const TimeStamp &ts=(*i)->get_timeout();
- if(ts<next_ts || !next)
- {
- next_ts=ts;
- next=*i;
- }
- }
- set_mutex.unlock();
-
- if(next)
- {
- const TimeStamp t=now();
- if(next_ts<=t || sem.wait(next_ts-t)==1)
- {
- if(next->signal_timeout.emit())
- next->timeout+=next->interval;
- else
- delete next;
- }
- }
+ slots.pop();
+ if(next->signal_timeout.emit() && next->increment())
+ slots.push(next);
else
- sem.wait();
+ delete next;
}
}
-/**
-Creates the thread if it doesn't exist, otherwise nudges it.
-*/
-void Timer::ThreadProxy::nudge()
+bool Timer::slot_compare(Slot *a, Slot *b)
{
- if(!thread)
- thread=new Thread();
- else
- thread->nudge();
+ return *a<*b;
}
-Timer::ThreadProxy::~ThreadProxy()
+
+Timer::Slot::Slot(const TimeDelta &td):
+ interval(td),
+ timeout(now()+interval)
+{ }
+
+Timer::Slot::Slot(const TimeStamp &ts):
+ timeout(ts)
+{ }
+
+bool Timer::Slot::increment()
{
- if(thread)
- {
- thread->finish();
- delete thread;
- }
+ if(!interval)
+ return false;
+ timeout+=interval;
+ return true;
+}
+
+bool Timer::Slot::operator<(const Slot &other) const
+{
+ return timeout<other.timeout;
}
} // namespace Time