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