]> git.sesse.net Git - casparcg/blob - common/concurrency/executor.h
2.1.0: Refactoring.
[casparcg] / common / concurrency / 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 "../log.h"\r
26 #include "../enum_class.h"\r
27 #include "../os/windows/windows.h"\r
28 \r
29 #include <tbb/atomic.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 namespace detail {\r
39         \r
40 template<typename T>\r
41 struct move_on_copy\r
42 {\r
43         move_on_copy(const move_on_copy<T>& other) : value(std::move(other.value)){}\r
44         move_on_copy(T&& value) : value(std::move(value)){}\r
45         mutable T value;\r
46 };\r
47 \r
48 template<typename T>\r
49 move_on_copy<T> make_move_on_copy(T&& value)\r
50 {\r
51         return move_on_copy<T>(std::move(value));\r
52 }\r
53 \r
54 }\r
55         \r
56 struct task_priority_def\r
57 {\r
58         enum type\r
59         {\r
60                 high_priority,\r
61                 normal_priority,\r
62                 priority_count\r
63         };\r
64 };\r
65 typedef enum_class<task_priority_def> task_priority;\r
66 \r
67 struct thread_priority_def\r
68 {\r
69         enum type\r
70         {\r
71                 high_priority_class,\r
72                 above_normal_priority_class,\r
73                 normal_priority_class,\r
74                 below_normal_priority_class\r
75         };\r
76 };\r
77 typedef enum_class<thread_priority_def> thread_priority;\r
78 \r
79 class executor\r
80 {\r
81         executor(const executor&);\r
82         executor& operator=(const executor&);\r
83 \r
84         const std::string name_;\r
85         boost::thread thread_;\r
86         tbb::atomic<bool> is_running_;\r
87         \r
88         typedef tbb::concurrent_bounded_queue<std::function<void()>> function_queue;\r
89         function_queue execution_queue_[task_priority::priority_count];\r
90                 \r
91         template<typename Func>\r
92         auto create_task(Func&& func) -> boost::packaged_task<decltype(func())> // noexcept\r
93         {       \r
94                 typedef boost::packaged_task<decltype(func())> task_type;\r
95                                 \r
96                 auto task = task_type(std::forward<Func>(func));\r
97                 \r
98                 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
99                 {\r
100                         try\r
101                         {\r
102                                 if(boost::this_thread::get_id() == thread_.get_id())  // Avoids potential deadlock.\r
103                                         my_task();\r
104                         }\r
105                         catch(boost::task_already_started&){}\r
106                 }));\r
107                                 \r
108                 return std::move(task);\r
109         }\r
110 \r
111 public:\r
112                 \r
113         explicit executor(const std::wstring& name) : name_(u8(name)) // noexcept\r
114         {\r
115                 is_running_ = true;\r
116                 thread_ = boost::thread([this]{run();});\r
117         }\r
118         \r
119         virtual ~executor() // noexcept\r
120         {\r
121                 stop();\r
122                 join();\r
123         }\r
124 \r
125         void set_capacity(size_t capacity) // noexcept\r
126         {\r
127                 execution_queue_[task_priority::normal_priority].set_capacity(capacity);\r
128         }\r
129 \r
130         void set_priority_class(thread_priority p)\r
131         {\r
132                 begin_invoke([=]\r
133                 {\r
134                         if(p == thread_priority::high_priority_class)\r
135                                 SetThreadPriority(GetCurrentThread(), HIGH_PRIORITY_CLASS);\r
136                         else if(p == thread_priority::above_normal_priority_class)\r
137                                 SetThreadPriority(GetCurrentThread(), ABOVE_NORMAL_PRIORITY_CLASS);\r
138                         else if(p == thread_priority::normal_priority_class)\r
139                                 SetThreadPriority(GetCurrentThread(), NORMAL_PRIORITY_CLASS);\r
140                         else if(p == thread_priority::below_normal_priority_class)\r
141                                 SetThreadPriority(GetCurrentThread(), BELOW_NORMAL_PRIORITY_CLASS);\r
142                 });\r
143         }\r
144         \r
145         void clear()\r
146         {               \r
147                 std::function<void()> func;\r
148                 while(execution_queue_[task_priority::normal_priority].try_pop(func));\r
149                 while(execution_queue_[task_priority::high_priority].try_pop(func));\r
150         }\r
151                                 \r
152         void stop() // noexcept\r
153         {\r
154                 is_running_ = false;    \r
155                 execution_queue_[task_priority::normal_priority].try_push([]{}); // Wake the execution thread.\r
156         }\r
157 \r
158         void wait() // noexcept\r
159         {\r
160                 invoke([]{});\r
161         }\r
162 \r
163         void join()\r
164         {\r
165                 if(boost::this_thread::get_id() == thread_.get_id())\r
166                         BOOST_THROW_EXCEPTION(invalid_operation());\r
167 \r
168                 thread_.join();\r
169         }\r
170                                 \r
171         template<typename Func>\r
172         auto begin_invoke(Func&& func, task_priority priority = task_priority::normal_priority) -> boost::unique_future<decltype(func())> // noexcept\r
173         {       \r
174                 if(!is_running_)\r
175                         BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("executor not running."));\r
176 \r
177                 // Create a move on copy adaptor to avoid copying the functor into the queue, tbb::concurrent_queue does not support move semantics.\r
178                 auto task_adaptor = detail::make_move_on_copy(create_task(func));\r
179 \r
180                 auto future = task_adaptor.value.get_future();\r
181 \r
182                 execution_queue_[priority.value()].push([=]\r
183                 {\r
184                         try\r
185                         {\r
186                                 task_adaptor.value();\r
187                         }\r
188                         catch(boost::task_already_started&)\r
189                         {\r
190                         }\r
191                         catch(...)\r
192                         {\r
193                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
194                         }\r
195                 });\r
196 \r
197                 if(priority != task_priority::normal_priority)\r
198                         execution_queue_[task_priority::normal_priority].push(nullptr);\r
199                                         \r
200                 return std::move(future);               \r
201         }\r
202         \r
203         template<typename Func>\r
204         auto invoke(Func&& func, task_priority prioriy = task_priority::normal_priority) -> decltype(func()) // noexcept\r
205         {\r
206                 if(boost::this_thread::get_id() == thread_.get_id())  // Avoids potential deadlock.\r
207                         return func();\r
208                 \r
209                 return begin_invoke(std::forward<Func>(func), prioriy).get();\r
210         }\r
211 \r
212         void yield() // noexcept\r
213         {\r
214                 if(boost::this_thread::get_id() != thread_.get_id())\r
215                         BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("Executor can only yield inside of thread context."));\r
216 \r
217                 std::function<void()> func;\r
218                 execution_queue_[task_priority::normal_priority].pop(func);     \r
219                 \r
220                 std::function<void()> func2;\r
221                 while(execution_queue_[task_priority::high_priority].try_pop(func2))\r
222                 {\r
223                         if(func2)\r
224                                 func2();\r
225                 }       \r
226 \r
227                 if(func)\r
228                         func();\r
229         }\r
230                 \r
231         function_queue::size_type size() const /*noexcept*/\r
232         {\r
233                 return execution_queue_[task_priority::normal_priority].size() + execution_queue_[task_priority::high_priority].size(); \r
234         }\r
235                 \r
236         bool is_running() const /*noexcept*/ { return is_running_; }    \r
237                 \r
238 private:        \r
239 \r
240         void run() // noexcept\r
241         {\r
242                 win32_exception::install_handler();             \r
243                 //detail::SetThreadName(GetCurrentThreadId(), name_.c_str());\r
244                 while(is_running_)\r
245                 {\r
246                         try\r
247                         {\r
248                                 yield();\r
249                         }\r
250                         catch(...)\r
251                         {\r
252                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
253                         }\r
254                 }\r
255         }       \r
256 };\r
257 \r
258 }