X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Ftime%2Ftimer.cpp;h=eda782e0d92c5bf82c00418584e12917d03fa673;hb=39da82b967c70282973025e4b12186625e29fe26;hp=f26900b8d4a589769c707b59513de6aa2d8dc129;hpb=aad3371b3d1831dd0525a51e40f637f00be6ff87;p=libs%2Fcore.git diff --git a/source/time/timer.cpp b/source/time/timer.cpp index f26900b..eda782e 100644 --- a/source/time/timer.cpp +++ b/source/time/timer.cpp @@ -1,4 +1,5 @@ -#include +#include +#include #include "timer.h" #include "utils.h" @@ -8,21 +9,20 @@ namespace Msp { namespace Time { Timer::Timer(): - sem(1), - blocking(false) + sem(1) { } Timer::~Timer() { - for(vector::iterator i=slots.begin(); i!=slots.end(); ++i) - delete i->slot; + for(const SlotProxy &s: slots) + delete s.slot; } Timer::Slot &Timer::add(const TimeDelta &td) { Slot *s = new Slot(td); MutexLock l(mutex); - slots.push_back(s); + slots.push_back({ s }); push_heap(slots.begin(), slots.end()); if(blocking) sem.signal(); @@ -33,7 +33,7 @@ Timer::Slot &Timer::add(const TimeStamp &ts) { Slot *s = new Slot(ts); MutexLock l(mutex); - slots.push_back(s); + slots.push_back({ s }); push_heap(slots.begin(), slots.end()); if(blocking) sem.signal(); @@ -43,47 +43,62 @@ Timer::Slot &Timer::add(const TimeStamp &ts) void Timer::cancel(Slot &slot) { MutexLock l(mutex); - for(vector::iterator i=slots.begin(); i!=slots.end(); ++i) - if(i->slot==&slot) - { - delete i->slot; - slots.erase(i); - make_heap(slots.begin(), slots.end()); - return; - } + auto i = find_member(slots, &slot, &SlotProxy::slot); + if(i!=slots.end()) + { + delete i->slot; + slots.erase(i); + make_heap(slots.begin(), slots.end()); + } +} + +void Timer::tick() +{ + do_tick(-sec); +} + +void Timer::tick(const TimeDelta &timeout) +{ + if(timeout=zero) + deadline = now()+timeout; + + Slot *next = nullptr; { MutexLock l(mutex); while(1) { - if(slots.empty()) + TimeStamp stamp; + TimeStamp t = now(); + if(!slots.empty()) { - if(block) - { - blocking = true; - mutex.unlock(); - sem.wait(); - mutex.lock(); - } - 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) + if(timeout && (!deadline || tsignal_timeout.emit() && next->increment()) { MutexLock l(mutex); - slots.push_back(next); + slots.push_back({ next }); push_heap(slots.begin(), slots.end()); } else @@ -137,10 +152,6 @@ bool Timer::Slot::increment() } -Timer::SlotProxy::SlotProxy(Slot *s): - slot(s) -{ } - bool Timer::SlotProxy::operator<(const SlotProxy &sp) const { return slot->get_timeout()>sp.slot->get_timeout();