1 // templated callback system
2 // Copyright (C) 2008, 2009 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 UTILITIES_CALLBACK_SYSTEM_HPP
20 #define UTILITIES_CALLBACK_SYSTEM_HPP
26 #include <boost/checked_delete.hpp>
28 #include <boost/lockfree/spsc_queue.hpp>
29 #include <boost/lockfree/queue.hpp>
34 /** \brief simple templated callback system, using a lockfree fifo */
35 template <class callback_type
,
37 class callback_deleter
= boost::checked_deleter
<callback_type
> >
38 class callback_system
:
39 private callback_deleter
41 typedef typename
boost::mpl::if_c
<mpmc
, boost::lockfree::queue
<callback_type
*>,
42 boost::lockfree::spsc_queue
<callback_type
*>
46 callback_system(size_t element_count
= 2048):
47 callbacks(element_count
)
50 /** \brief adds a new Callback to the Scheduler, threadsafe */
51 inline void add_callback(callback_type
* cb
)
56 /** \brief run all callbacks */
57 inline void run_callbacks(void)
62 if (not callbacks
.pop(runme
))
69 /** \brief run one callback
71 * assumes, that the queue contains at least one callback
74 void run_callback(void)
77 bool dequeued
= callbacks
.pop(&runme
);
84 /** run a callback, handle exceptions */
85 bool run_callback(callback_type
* runme
)
91 } catch(std::exception
const & e
) {
92 std::cerr
<< "unhandled exception while running callback: " << e
.what() << std::endl
;
95 callback_deleter::operator()(runme
);
100 queue_type callbacks
; /**< \brief fifo for callbacks */
103 } /* namespace nova */
105 #endif /* UTILITIES_CALLBACK_SYSTEM_HPP */