/*] Copyright (c) 2009-2011, Charles McGarvey [***************************** **] All rights reserved. * * Distributable under the terms and conditions of the 2-clause BSD license; * see the file COPYING for a complete text of the license. * *****************************************************************************/ #if HAVE_CONFIG_H #include "config.h" #endif #include #include "hash.hh" #include "log.hh" #include "runloop.hh" #include "timer.hh" namespace moof { bool comp(timer* a, timer* b) { return a->expiration() < b->expiration(); } int runloop::run_once() { #if ENABLE_THREADS thread_id_ = thread::current_identifier(); #endif //log_debug("------------------------------------"); int expired = 0; MOOF_MUTEX_LOCK(timers_mutex_); std::sort(timers_.begin(), timers_.end(), comp); for (timers_it_ = timers_.begin(); timers_it_ != timers_.end(); ++timers_it_) { if ((*timers_it_)->fire_if_expired()) ++expired; } return expired; } int runloop::run() { stop_ = false; while (!stop_) { if (run_once() == 0);//timer::sleep(SCALAR(0.0)); // TODO: maybe sleep(0.0001) will actually return sooner than // sleep(0)... if the kernel interprets sleep(0) as we don't need // to process for an arbitrarily long timespan while specifying a // value lets the kernel know when we need control back... } return code_; } void runloop::stop(int code) { code_ = code; stop_ = true; } void runloop::add_timer(timer& timer) { #if ENABLE_THREADS if (thread_id_ != thread::current_identifier()) { MOOF_MUTEX_LOCK(timers_mutex_); timers_.push_back(&timer); timers_it_ = timers_.end(); } else #endif { timers_.push_back(&timer); timers_it_ = timers_.end(); } } void runloop::remove_timer(timer& timer) { #if ENABLE_THREADS if (thread_id_ != thread::current_identifier()) { MOOF_MUTEX_LOCK(timers_mutex_); timers_.erase(std::find(timers_.begin(), timers_.end(), &timer)); timers_it_ = timers_.end(); } else #endif { timers_.erase(std::find(timers_.begin(), timers_.end(), &timer)); timers_it_ = timers_.end(); } } } // namespace moof