X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Ftime%2Ftimer.cpp;h=04c3074494e921d39f3edb54e53e378c8623e826;hp=ab5305948cd7d2040416208cb689ba0a716ef5c8;hb=HEAD;hpb=b56eb5ec1da675da0c66abc53c1e4f6c4e4cccbd diff --git a/source/time/timer.cpp b/source/time/timer.cpp index ab53059..eda782e 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 #include "timer.h" #include "utils.h" @@ -14,70 +8,98 @@ using namespace std; namespace Msp { namespace Time { +Timer::Timer(): + 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); - mutex.lock(); - slots.push_back(s); + 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(); + MutexLock l(mutex); + slots.push_back({ s }); + push_heap(slots.begin(), slots.end()); + if(blocking) + sem.signal(); return *s; } 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(bool block) +void Timer::tick() { - Slot *next = 0; + 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) - 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(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 @@ -130,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();