// scheduler.cc // {{{ // // Copyright (C) 2004 Nicolas Schodet // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Contact : // Web: http://perso.efrei.fr/~schodet/ // Email: // }}} #include "scheduler.hh" #include "utils/fd_set.hh" #include "timer/timer.hh" #include #include namespace scheduler { /// Destructeur. Scheduler::~Scheduler (void) { // TODO: Test for schedulables_ empty ? } /// Ajoute un élément schedulable. void Scheduler::insert (Schedulable &schedulable) { schedulables_.insert (&schedulable); } /// Enlève un élément schedulable. void Scheduler::erase (Schedulable &schedulable) { schedulables_.erase (&schedulable); } /// Lance le scheduler. Si timeout est différent de -1, c'est le temps /// maximal que prend le scheduler avant de rendre la main. Si /// returnOnEvent est true, le premier évenement arrète le scheduler. /// Renvois true si au moins un événement a été traité. bool Scheduler::schedule (int timeout/*-1*/, bool returnOnEvent/*false*/) { bool event = false; int t = Timer::getProgramTime (); int start = t; do { // Prépare le select. int to = timeout == -1 ? -1 : start + timeout - t; FdSet readFds; for (Schedulables::const_iterator i = schedulables_.begin (); i != schedulables_.end (); ++i) { int top = -1; (*i)->setup (*this, t, readFds, top); // Si le timeout est plus court, retient ce timeout. if (to == -1 || top != -1 && top < to) to = top; } // Select. if (to != -1) { timeval tv; tv.tv_sec = to / 1000; tv.tv_usec = to % 1000 * 1000; select (FD_SETSIZE, readFds.get (), 0, 0, &tv); } else { select (FD_SETSIZE, readFds.get (), 0, 0, 0); } // Run. t = Timer::getProgramTime (); for (Schedulables::const_iterator i = schedulables_.begin (); i != schedulables_.end (); ++i) event = (*i)->run (*this, t, readFds) || event; t = Timer::getProgramTime (); } while (!(returnOnEvent && event) && (timeout == -1 || start + timeout > t)); return event; } } // namespace scheduler