]> git.sesse.net Git - casparcg/blob - common/concurrency/executor.h
2.0.0.2: - write_frame: Optimized header includes.
[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/assert.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 priority\r
65 {\r
66         high_priority,\r
67         normal_priority,\r
68         priority_count\r
69 };\r
70 \r
71 namespace internal\r
72 {\r
73         template<typename T>\r
74         struct move_on_copy\r
75         {\r
76                 move_on_copy(const move_on_copy<T>& other) : value(std::move(other.value)){}\r
77                 move_on_copy(T&& value) : value(std::move(value)){}\r
78                 mutable T value;\r
79         };\r
80 \r
81         template<typename T>\r
82         move_on_copy<T> make_move_on_copy(T&& value)\r
83         {\r
84                 return move_on_copy<T>(std::move(value));\r
85         }\r
86 }\r
87 \r
88 class executor : boost::noncopyable\r
89 {\r
90         const std::string name_;\r
91         boost::thread thread_;\r
92         tbb::atomic<bool> is_running_;\r
93         \r
94         typedef tbb::concurrent_bounded_queue<std::function<void()>> function_queue;\r
95         function_queue execution_queue_[priority_count];\r
96                 \r
97         template<typename Func>\r
98         auto create_task(Func&& func) -> boost::packaged_task<decltype(func())> // noexcept\r
99         {       \r
100                 typedef boost::packaged_task<decltype(func())> task_type;\r
101                                 \r
102                 auto task = task_type(std::forward<Func>(func));\r
103                 \r
104                 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
105                 {\r
106                         try\r
107                         {\r
108                                 if(boost::this_thread::get_id() == thread_.get_id())  // Avoids potential deadlock.\r
109                                         my_task();\r
110                         }\r
111                         catch(boost::task_already_started&){}\r
112                 }));\r
113                                 \r
114                 return std::move(task);\r
115         }\r
116 \r
117 public:\r
118                 \r
119         explicit executor(const std::wstring& name) : name_(narrow(name)) // noexcept\r
120         {\r
121                 thread_ = boost::thread([this]{run();});\r
122                 is_running_ = true;\r
123         }\r
124         \r
125         virtual ~executor() // noexcept\r
126         {\r
127                 stop();\r
128                 join();\r
129         }\r
130 \r
131         void set_capacity(size_t capacity) // noexcept\r
132         {\r
133                 execution_queue_[normal_priority].set_capacity(capacity);\r
134         }\r
135                                 \r
136         void stop() // noexcept\r
137         {\r
138                 is_running_ = false;    \r
139                 execution_queue_[normal_priority].try_push([]{}); // Wake the execution thread.\r
140         }\r
141 \r
142         void wait() // noexcept\r
143         {\r
144                 invoke([]{});\r
145         }\r
146 \r
147         void join()\r
148         {\r
149                 if(boost::this_thread::get_id() != thread_.get_id())\r
150                         thread_.join();\r
151         }\r
152                                 \r
153         template<typename Func>\r
154         auto begin_invoke(Func&& func, priority priority = normal_priority) -> boost::unique_future<decltype(func())> // noexcept\r
155         {       \r
156                 // Create a move on copy adaptor to avoid copying the functor into the queue, tbb::concurrent_queue does not support move semantics.\r
157                 auto task_adaptor = internal::make_move_on_copy(create_task(func));\r
158 \r
159                 auto future = task_adaptor.value.get_future();\r
160 \r
161                 execution_queue_[priority].push([=]\r
162                 {\r
163                         try{task_adaptor.value();}\r
164                         catch(boost::task_already_started&){}\r
165                         catch(...){CASPAR_LOG_CURRENT_EXCEPTION();}\r
166                 });\r
167 \r
168                 if(priority != normal_priority)\r
169                         execution_queue_[normal_priority].push(nullptr);\r
170                                         \r
171                 return std::move(future);               \r
172         }\r
173 \r
174         template<typename Func>\r
175         auto try_begin_invoke(Func&& func, priority priority = normal_priority) -> boost::unique_future<decltype(func())> // noexcept\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 = internal::make_move_on_copy(create_task(func));\r
179                 \r
180                 auto future = task_adaptor.value.get_future();\r
181 \r
182                 if(priority == normal_priority || execution_queue_[normal_priority].try_push(nullptr))\r
183                 {                       \r
184                         execution_queue_[priority].try_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                 \r
192                 return std::move(future);                       \r
193         }\r
194 \r
195         template<typename Func>\r
196         auto invoke(Func&& func, priority prioriy = normal_priority) -> decltype(func()) // noexcept\r
197         {\r
198                 if(boost::this_thread::get_id() == thread_.get_id())  // Avoids potential deadlock.\r
199                         return func();\r
200                 \r
201                 return begin_invoke(std::forward<Func>(func), prioriy).get();\r
202         }\r
203 \r
204         template<typename Func>\r
205         auto try_invoke(Func&& func, priority prioriy = normal_priority) -> decltype(func()) // noexcept\r
206         {\r
207                 if(boost::this_thread::get_id() == thread_.get_id())  // Avoids potential deadlock.\r
208                         return func();\r
209                 \r
210                 return try_begin_invoke(std::forward<Func>(func), prioriy).get();\r
211         }\r
212 \r
213         void yield() // noexcept\r
214         {\r
215                 if(boost::this_thread::get_id() != thread_.get_id())  // Only yield when calling from execution thread.\r
216                         return;\r
217 \r
218                 std::function<void()> func;\r
219                 while(execution_queue_[high_priority].try_pop(func))\r
220                 {\r
221                         if(func)\r
222                                 func();\r
223                 }       \r
224         }\r
225         \r
226         function_queue::size_type capacity() const /*noexcept*/ { return execution_queue_[normal_priority].capacity();  }\r
227         function_queue::size_type size() const /*noexcept*/ { return execution_queue_[normal_priority].size();  }\r
228         bool empty() const /*noexcept*/ { return execution_queue_[normal_priority].empty();     }\r
229         bool is_running() const /*noexcept*/ { return is_running_; }    \r
230                 \r
231 private:\r
232         \r
233         void execute() // noexcept\r
234         {\r
235                 std::function<void()> func;\r
236                 execution_queue_[normal_priority].pop(func);    \r
237 \r
238                 yield();\r
239 \r
240                 if(func)\r
241                         func();\r
242         }\r
243 \r
244         void run() // noexcept\r
245         {\r
246                 win32_exception::install_handler();             \r
247                 detail::SetThreadName(GetCurrentThreadId(), name_.c_str());\r
248                 while(is_running_)\r
249                         execute();\r
250         }       \r
251 };\r
252 \r
253 }