X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Ftime%2Ftimer.cpp;h=7c9567ecfecccafe826f8d1fcd52d0bb82d6f899;hp=9471463216206b701d285562bb41e0af1901fafc;hb=ac26a7e3db27d27ea322ccc17bb093b348b30ae8;hpb=5889d53f8f073ff0e1e1ebbd786abecd8352a7b3 diff --git a/source/time/timer.cpp b/source/time/timer.cpp index 9471463..7c9567e 100644 --- a/source/time/timer.cpp +++ b/source/time/timer.cpp @@ -1,11 +1,5 @@ -/* $Id$ - -This file is part of libmspcore -Copyright © 2006, 2009 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #include +#include #include "timer.h" #include "utils.h" @@ -14,6 +8,11 @@ using namespace std; namespace Msp { namespace Time { +Timer::Timer(): + sem(1), + blocking(false) +{ } + Timer::~Timer() { for(vector::iterator i=slots.begin(); i!=slots.end(); ++i) @@ -22,24 +21,23 @@ Timer::~Timer() Timer::Slot &Timer::add(const TimeDelta &td) { - Slot *s=new Slot(td); - mutex.lock(); + Slot *s = new Slot(td); + MutexLock l(mutex); slots.push_back(s); push_heap(slots.begin(), slots.end()); - mutex.unlock(); - sem.signal(); + if(blocking) + sem.signal(); return *s; } Timer::Slot &Timer::add(const TimeStamp &ts) { - Slot *s=new Slot(ts); - { - MutexLock l(mutex); - slots.push_back(s); - push_heap(slots.begin(), slots.end()); - } - sem.signal(); + Slot *s = new Slot(ts); + MutexLock l(mutex); + slots.push_back(s); + push_heap(slots.begin(), slots.end()); + if(blocking) + sem.signal(); return *s; } @@ -58,26 +56,33 @@ void Timer::cancel(Slot &slot) void Timer::tick(bool block) { - Slot *next=0; + Slot *next = 0; { MutexLock l(mutex); while(1) { - if(slots.empty()) + TimeStamp stamp; + TimeStamp t = now(); + if(!slots.empty()) { - if(block) - sem.wait(); - else - return; + next = slots.begin()->slot; + stamp = next->get_timeout(); + if(stamp<=t) + break; } - next=slots.begin()->slot; - const TimeStamp &stamp=next->get_timeout(); - const TimeStamp t=now(); - if(stamp<=t) - break; - else if(block) - sem.wait(stamp-t); + if(block) + { + SetFlag setf(blocking); + mutex.unlock(); + if(stamp) + sem.wait(stamp-t); + else + sem.wait(); + mutex.lock(); + // The slots may have changed while waiting so check again + continue; + } else return; } @@ -125,7 +130,7 @@ bool Timer::Slot::increment() { if(!interval) return false; - timeout+=interval; + timeout += interval; return true; }