]> git.sesse.net Git - casparcg/blob - common/executor.h
2.1.0: -common: Restructured files. Moved most files into root for easier inclusion...
[casparcg] / common / executor.h
1 /*\r
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\r
5 *\r
6 * CasparCG is free software: you can redistribute it and/or modify\r
7 * it under the terms of the GNU General Public License as published by\r
8 * the Free Software Foundation, either version 3 of the License, or\r
9 * (at your option) any later version.\r
10 *\r
11 * CasparCG is distributed in the hope that it will be useful,\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 * GNU General Public License for more details.\r
15 *\r
16 * You should have received a copy of the GNU General Public License\r
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.\r
18 *\r
19 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21 \r
22 #pragma once\r
23 \r
24 #include "except.h"\r
25 #include "enum_class.h"\r
26 #include "log.h"\r
27 \r
28 #include <tbb/atomic.h>\r
29 #include <tbb/concurrent_priority_queue.h>\r
30 #include <tbb/concurrent_queue.h>\r
31 \r
32 #include <boost/thread.hpp>\r
33 \r
34 #include <functional>\r
35 \r
36 namespace caspar {\r
37                 \r
38 struct task_priority_def\r
39 {\r
40         enum type\r
41         {\r
42                 lower_priority = 1,\r
43                 low_priority,\r
44                 normal_priority,\r
45                 high_priority,\r
46                 higher_priority\r
47         };\r
48 };\r
49 typedef enum_class<task_priority_def> task_priority;\r
50 \r
51 class executor\r
52 {       \r
53         struct priority_function\r
54         {\r
55                 int                                             priority;\r
56                 std::function<void()>   func;\r
57 \r
58                 priority_function()\r
59                 {\r
60                 }\r
61 \r
62                 template<typename F>\r
63                 priority_function(int priority, F&& func)\r
64                         : priority(priority)\r
65                         , func(std::forward<F>(func))\r
66                 {\r
67                 }\r
68 \r
69                 void operator()()\r
70                 {\r
71                         func();\r
72                 }\r
73 \r
74                 bool operator<(const priority_function& other) const\r
75                 {\r
76                         return priority < other.priority;\r
77                 }\r
78         };\r
79 \r
80         executor(const executor&);\r
81         executor& operator=(const executor&);\r
82         \r
83         typedef tbb::concurrent_priority_queue<priority_function>       function_queue_t;\r
84 \r
85         tbb::atomic<bool>                                                                                       is_running_;\r
86         boost::thread                                                                                           thread_;        \r
87         function_queue_t                                                                                        execution_queue_;\r
88         tbb::concurrent_bounded_queue<int>                                                      semaphore_;\r
89                 \r
90 public:         \r
91         executor(const std::wstring& name) // noexcept\r
92         {\r
93                 name; // TODO: Use to set thread name.\r
94                 is_running_ = true;\r
95                 thread_ = boost::thread([this]{run();});\r
96         }\r
97         \r
98         virtual ~executor() // noexcept\r
99         {\r
100                 stop();\r
101                 thread_.join();\r
102         }\r
103                                                 \r
104         template<typename Func>\r
105         auto begin_invoke(Func&& func, task_priority priority = task_priority::normal_priority) -> boost::unique_future<decltype(func())> // noexcept\r
106         {       \r
107                 if(!is_running_)\r
108                         BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("executor not running."));\r
109                                 \r
110                 typedef typename std::remove_reference<Func>::type      function_type;\r
111                 typedef decltype(func())                                                        result_type;\r
112                 typedef boost::packaged_task<result_type>                       task_type;\r
113                                                                 \r
114                 std::unique_ptr<task_type> task;\r
115 \r
116                 // Use pointers since the boost thread library doesn't fully support move semantics.\r
117 \r
118                 auto raw_func2 = new function_type(std::forward<Func>(func));\r
119                 try\r
120                 {\r
121                         task.reset(new task_type([raw_func2]() -> result_type\r
122                         {\r
123                                 std::unique_ptr<function_type> func2(raw_func2);\r
124                                 return (*func2)();\r
125                         }));\r
126                 }\r
127                 catch(...)\r
128                 {\r
129                         delete raw_func2;\r
130                         throw;\r
131                 }\r
132                 \r
133                 task->set_wait_callback(std::function<void(task_type&)>([=](task_type& my_task) // The std::function wrapper is required in order to add ::result_type to functor class.\r
134                 {\r
135                         try\r
136                         {\r
137                                 if(is_current())  // Avoids potential deadlock.\r
138                                         my_task();\r
139                         }\r
140                         catch(boost::task_already_started&){}\r
141                 }));\r
142                                 \r
143                 auto future = task->get_future();\r
144 \r
145                 auto raw_task = task.release();\r
146                 priority_function prio_func(priority.value(), [raw_task]\r
147                 {\r
148                         std::unique_ptr<task_type> task(raw_task);\r
149                         try\r
150                         {\r
151                                 (*task)();\r
152                         }\r
153                         catch(boost::task_already_started&){}\r
154                 });\r
155 \r
156                 execution_queue_.push(prio_func);\r
157                 semaphore_.push(0);\r
158                                                         \r
159                 return std::move(future);               \r
160         }\r
161         \r
162         template<typename Func>\r
163         auto invoke(Func&& func, task_priority prioriy = task_priority::normal_priority) -> decltype(func()) // noexcept\r
164         {\r
165                 if(is_current())  // Avoids potential deadlock.\r
166                         return func();\r
167                 \r
168                 return begin_invoke(std::forward<Func>(func), prioriy).get();\r
169         }\r
170 \r
171         void yield() // noexcept\r
172         {\r
173                 if(!is_current())\r
174                         BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("Executor can only yield inside of thread context."));\r
175 \r
176                 int dummy;\r
177                 semaphore_.pop(dummy);\r
178 \r
179                 priority_function func;\r
180                 if(execution_queue_.try_pop(func))\r
181                         func();\r
182         }\r
183 \r
184         void set_capacity(std::size_t capacity) // noexcept\r
185         {\r
186                 semaphore_.set_capacity(capacity);\r
187         }\r
188 \r
189         std::size_t capacity() const\r
190         {\r
191                 return semaphore_.capacity();\r
192         }\r
193         \r
194         void clear()\r
195         {               \r
196                 priority_function func;\r
197                 while(execution_queue_.try_pop(func));\r
198         }\r
199                                 \r
200         void stop()\r
201         {\r
202                 invoke([this]\r
203                 {\r
204                         is_running_ = false;\r
205                 });\r
206         }\r
207 \r
208         void wait()\r
209         {\r
210                 invoke([]{});\r
211         }\r
212                 \r
213         function_queue_t::size_type size() const \r
214         {\r
215                 return execution_queue_.size(); \r
216         }\r
217                 \r
218         bool is_running() const\r
219         {\r
220                 return is_running_; \r
221         }       \r
222 \r
223         bool is_current() const\r
224         {\r
225                 return boost::this_thread::get_id() == thread_.get_id();\r
226         }\r
227                 \r
228 private:        \r
229 \r
230         void run() // noexcept\r
231         {\r
232                 win32_exception::install_handler();             \r
233                 while(is_running_)\r
234                 {\r
235                         try\r
236                         {\r
237                                 yield();\r
238                         }\r
239                         catch(...)\r
240                         {\r
241                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
242                         }\r
243                 }\r
244         }       \r
245 };\r
246 \r
247 }