1 // ticket-based scheduler
2 // Copyright (C) 2007, 2008 Tim Blechmann
4 // This program is free software; you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation; either version 2 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program; see the file COPYING. If not, write to
16 // the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 // Boston, MA 02111-1307, USA.
19 #ifndef TICKET_SCHEDULER_HPP
20 #define TICKET_SCHEDULER_HPP
22 #include <boost/noncopyable.hpp>
23 #include <boost/atomic.hpp>
24 #include <boost/thread/condition.hpp>
25 #include <boost/date_time/posix_time/ptime.hpp>
32 class ticket_scheduler
:
35 typedef std::size_t size_t;
36 typedef boost::atomic
<size_t> atomic_int
;
39 size_t get_ticket(void)
41 return ticket_source
++;
44 template <class functor
>
45 bool run_nonblocking(size_t ticket
, functor
const & f
)
47 if (ticket
== current_ticket
)
55 template <class functor
>
56 void run(size_t ticket
, functor
const & f
)
58 boost::mutex::scoped_lock
lock(mutex
);
59 while (ticket
!= current_ticket
)
61 /* now this is ugly ... however, just waiting for the event results in a deadlock
62 * if the notification occurs before the wait operation
63 * semaphores are resistant against this problem, but harder to use for a ticket
64 * scheduling algorithm (would require thread-specific semaphores)
66 cond
.timed_wait(lock
, boost::posix_time::milliseconds(100));
73 template <class functor
>
74 void run_functor(functor
const & f
)
81 atomic_int ticket_source
;
82 atomic_int current_ticket
;
85 boost::condition cond
;
88 } /* namespace nova */
91 #endif /* TICKET_SCHEDULER_HPP */