]> git.sesse.net Git - casparcg/blob - common/concurrency/executor.h
c4ba4008f95af44af38d5601afed9a238813af0c
[casparcg] / common / concurrency / executor.h
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\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 */\r
20 #pragma once\r
21 \r
22 #include "../exception/win32_exception.h"\r
23 #include "../utility/string.h"\r
24 #include "../log/log.h"\r
25 \r
26 #include <tbb/atomic.h>\r
27 #include <tbb/concurrent_queue.h>\r
28 \r
29 #include <boost/thread.hpp>\r
30 #include <boost/noncopyable.hpp>\r
31 \r
32 #include <functional>\r
33 \r
34 namespace caspar {\r
35 \r
36 namespace detail {\r
37 \r
38 typedef struct tagTHREADNAME_INFO\r
39 {\r
40         DWORD dwType; // must be 0x1000\r
41         LPCSTR szName; // pointer to name (in user addr space)\r
42         DWORD dwThreadID; // thread ID (-1=caller thread)\r
43         DWORD dwFlags; // reserved for future use, must be zero\r
44 } THREADNAME_INFO;\r
45 \r
46 inline void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName)\r
47 {\r
48         THREADNAME_INFO info;\r
49         {\r
50                 info.dwType = 0x1000;\r
51                 info.szName = szThreadName;\r
52                 info.dwThreadID = dwThreadID;\r
53                 info.dwFlags = 0;\r
54         }\r
55         __try\r
56         {\r
57                 RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (DWORD*)&info );\r
58         }\r
59         __except (EXCEPTION_CONTINUE_EXECUTION){}       \r
60 }\r
61 \r
62 }\r
63 \r
64 enum task_priority\r
65 {\r
66         high_priority,\r
67         normal_priority,\r
68         priority_count\r
69 };\r
70 \r
71 enum thread_priority\r
72 {\r
73         high_priority_class,\r
74         above_normal_priority_class,\r
75         normal_priority_class,\r
76         below_normal_priority_class\r
77 };\r
78 \r
79 namespace internal\r
80 {\r
81         template<typename T>\r
82         struct move_on_copy\r
83         {\r
84                 move_on_copy(const move_on_copy<T>& other) : value(std::move(other.value)){}\r
85                 move_on_copy(T&& value) : value(std::move(value)){}\r
86                 mutable T value;\r
87         };\r
88 \r
89         template<typename T>\r
90         move_on_copy<T> make_move_on_copy(T&& value)\r
91         {\r
92                 return move_on_copy<T>(std::move(value));\r
93         }\r
94 }\r
95 \r
96 class executor : boost::noncopyable\r
97 {\r
98         const std::string name_;\r
99         boost::thread thread_;\r
100         tbb::atomic<bool> is_running_;\r
101         \r
102         typedef tbb::concurrent_bounded_queue<std::function<void()>> function_queue;\r
103         function_queue execution_queue_[priority_count];\r
104                 \r
105         template<typename Func>\r
106         auto create_task(Func&& func) -> boost::packaged_task<decltype(func())> // noexcept\r
107         {       \r
108                 typedef boost::packaged_task<decltype(func())> task_type;\r
109                                 \r
110                 auto task = task_type(std::forward<Func>(func));\r
111                 \r
112                 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
113                 {\r
114                         try\r
115                         {\r
116                                 if(boost::this_thread::get_id() == thread_.get_id())  // Avoids potential deadlock.\r
117                                         my_task();\r
118                         }\r
119                         catch(boost::task_already_started&){}\r
120                 }));\r
121                                 \r
122                 return std::move(task);\r
123         }\r
124 \r
125 public:\r
126                 \r
127         explicit executor(const std::wstring& name) : name_(narrow(name)) // noexcept\r
128         {\r
129                 thread_ = boost::thread([this]{run();});\r
130                 is_running_ = true;\r
131         }\r
132         \r
133         virtual ~executor() // noexcept\r
134         {\r
135                 stop();\r
136                 join();\r
137         }\r
138 \r
139         void set_capacity(size_t capacity) // noexcept\r
140         {\r
141                 execution_queue_[normal_priority].set_capacity(capacity);\r
142         }\r
143 \r
144         void set_priority_class(thread_priority p)\r
145         {\r
146                 begin_invoke([=]\r
147                 {\r
148                         if(p == high_priority_class)\r
149                                 SetThreadPriority(GetCurrentThread(), HIGH_PRIORITY_CLASS);\r
150                         if(p == above_normal_priority_class)\r
151                                 SetThreadPriority(GetCurrentThread(), ABOVE_NORMAL_PRIORITY_CLASS);\r
152                         else if(p == normal_priority_class)\r
153                                 SetThreadPriority(GetCurrentThread(), NORMAL_PRIORITY_CLASS);\r
154                         else if(p == below_normal_priority_class)\r
155                                 SetThreadPriority(GetCurrentThread(), BELOW_NORMAL_PRIORITY_CLASS);\r
156                 });\r
157         }\r
158                                 \r
159         void stop() // noexcept\r
160         {\r
161                 is_running_ = false;    \r
162                 execution_queue_[normal_priority].try_push([]{}); // Wake the execution thread.\r
163         }\r
164 \r
165         void wait() // noexcept\r
166         {\r
167                 invoke([]{});\r
168         }\r
169 \r
170         void join()\r
171         {\r
172                 if(boost::this_thread::get_id() != thread_.get_id())\r
173                         thread_.join();\r
174         }\r
175                                 \r
176         template<typename Func>\r
177         auto begin_invoke(Func&& func, task_priority priority = normal_priority) -> boost::unique_future<decltype(func())> // noexcept\r
178         {       \r
179                 // Create a move on copy adaptor to avoid copying the functor into the queue, tbb::concurrent_queue does not support move semantics.\r
180                 auto task_adaptor = internal::make_move_on_copy(create_task(func));\r
181 \r
182                 auto future = task_adaptor.value.get_future();\r
183 \r
184                 execution_queue_[priority].push([=]\r
185                 {\r
186                         try{task_adaptor.value();}\r
187                         catch(boost::task_already_started&){}\r
188                         catch(...){CASPAR_LOG_CURRENT_EXCEPTION();}\r
189                 });\r
190 \r
191                 if(priority != normal_priority)\r
192                         execution_queue_[normal_priority].push(nullptr);\r
193                                         \r
194                 return std::move(future);               \r
195         }\r
196 \r
197         template<typename Func>\r
198         auto try_begin_invoke(Func&& func, task_priority priority = normal_priority) -> boost::unique_future<decltype(func())> // noexcept\r
199         {\r
200                 // Create a move on copy adaptor to avoid copying the functor into the queue, tbb::concurrent_queue does not support move semantics.\r
201                 auto task_adaptor = internal::make_move_on_copy(create_task(func));\r
202                 \r
203                 auto future = task_adaptor.value.get_future();\r
204 \r
205                 if(priority == normal_priority || execution_queue_[normal_priority].try_push(nullptr))\r
206                 {                       \r
207                         execution_queue_[priority].try_push([=]\r
208                         {\r
209                                 try{task_adaptor.value();}\r
210                                 catch(boost::task_already_started&){}\r
211                                 catch(...){CASPAR_LOG_CURRENT_EXCEPTION();}\r
212                         });\r
213                 }\r
214                 \r
215                 return std::move(future);                       \r
216         }\r
217 \r
218         template<typename Func>\r
219         auto invoke(Func&& func, task_priority prioriy = normal_priority) -> decltype(func()) // noexcept\r
220         {\r
221                 if(boost::this_thread::get_id() == thread_.get_id())  // Avoids potential deadlock.\r
222                         return func();\r
223                 \r
224                 return begin_invoke(std::forward<Func>(func), prioriy).get();\r
225         }\r
226 \r
227         template<typename Func>\r
228         auto try_invoke(Func&& func, task_priority prioriy = normal_priority) -> decltype(func()) // noexcept\r
229         {\r
230                 if(boost::this_thread::get_id() == thread_.get_id())  // Avoids potential deadlock.\r
231                         return func();\r
232                 \r
233                 return try_begin_invoke(std::forward<Func>(func), prioriy).get();\r
234         }\r
235 \r
236         void yield() // noexcept\r
237         {\r
238                 if(boost::this_thread::get_id() != thread_.get_id())  // Only yield when calling from execution thread.\r
239                         return;\r
240 \r
241                 std::function<void()> func;\r
242                 while(execution_queue_[high_priority].try_pop(func))\r
243                 {\r
244                         if(func)\r
245                                 func();\r
246                 }       \r
247         }\r
248         \r
249         function_queue::size_type capacity() const /*noexcept*/ { return execution_queue_[normal_priority].capacity();  }\r
250         function_queue::size_type size() const /*noexcept*/ { return execution_queue_[normal_priority].size();  }\r
251         bool empty() const /*noexcept*/ { return execution_queue_[normal_priority].empty();     }\r
252         bool is_running() const /*noexcept*/ { return is_running_; }    \r
253                 \r
254 private:\r
255         \r
256         void execute() // noexcept\r
257         {\r
258                 std::function<void()> func;\r
259                 execution_queue_[normal_priority].pop(func);    \r
260 \r
261                 yield();\r
262 \r
263                 if(func)\r
264                         func();\r
265         }\r
266 \r
267         void run() // noexcept\r
268         {\r
269                 win32_exception::install_handler();             \r
270                 detail::SetThreadName(GetCurrentThreadId(), name_.c_str());\r
271                 while(is_running_)\r
272                 {\r
273                         try\r
274                         {\r
275                                 execute();\r
276                         }\r
277                         catch(...)\r
278                         {\r
279                                 CASPAR_LOG_CURRENT_EXCEPTION();\r
280                         }\r
281                 }\r
282         }       \r
283 };\r
284 \r
285 }