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