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