X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Ftime%2Ftimer.cpp;h=be1d1ed3291482b453ab03d228f5961eb80b8cab;hp=ab5305948cd7d2040416208cb689ba0a716ef5c8;hb=108f2e7de1c2427e39cdf55efbcd0ca3914e451a;hpb=b56eb5ec1da675da0c66abc53c1e4f6c4e4cccbd diff --git a/source/time/timer.cpp b/source/time/timer.cpp index ab53059..be1d1ed 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) @@ -23,23 +22,22 @@ Timer::~Timer() Timer::Slot &Timer::add(const TimeDelta &td) { Slot *s = new Slot(td); - mutex.lock(); + 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; } @@ -58,26 +56,57 @@ void Timer::cancel(Slot &slot) void Timer::tick(bool block) { + if(block) + tick(); + else + tick(zero); +} + +void Timer::tick() +{ + do_tick(-sec); +} + +void Timer::tick(const TimeDelta &timeout) +{ + do_tick(timeout); +} + +void Timer::do_tick(const TimeDelta &timeout) +{ + TimeStamp deadline; + if(timeout>=zero) + deadline = now()+timeout; + 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(timeout && (!deadline || t