bumping version to 3.5-rc1
[supercollider.git] / server / supernova / utilities / callback_system.hpp
blob53db3657a9d597cc4a223064a9661a764366d494
1 // templated callback system
2 // Copyright (C) 2008, 2009 Tim Blechmann
3 //
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.
8 //
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
22 #include <memory>
23 #include <exception>
24 #include <iostream>
26 #include <boost/checked_delete.hpp>
28 #include <boost/lockfree/ringbuffer.hpp>
29 #include <boost/lockfree/fifo.hpp>
32 namespace nova {
34 /** \brief simple templated callback system, using a lockfree fifo */
35 template <class callback_type,
36 bool mpmc = true,
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::fifo<callback_type*>,
42 boost::lockfree::ringbuffer<callback_type*, 0>
43 >::type queue_type;
45 public:
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)
53 callbacks.enqueue(cb);
56 /** \brief run all callbacks */
57 inline void run_callbacks(void)
59 for (;;) {
60 callback_type* runme;
62 if (not callbacks.dequeue(runme))
63 break;
65 run_callback(runme);
69 /** \brief run one callback
71 * assumes, that the queue contains at least one callback
73 * */
74 void run_callback(void)
76 callback_type* runme;
77 bool dequeued = callbacks.dequeue(&runme);
78 assert(dequeued);
80 run_callback(runme);
83 private:
84 /** run a callback, handle exceptions */
85 bool run_callback(callback_type * runme)
87 bool ret;
88 try {
89 runme->run();
90 ret = true;
91 } catch(std::exception const & e) {
92 std::cerr << "unhandled exception while running callback: " << e.what() << std::endl;
93 ret = false;
95 callback_deleter::operator()(runme);
96 return ret;
99 protected:
100 queue_type callbacks; /**< \brief fifo for callbacks */
103 } /* namespace nova */
105 #endif /* UTILITIES_CALLBACK_SYSTEM_HPP */