c++-gtk-utils

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

async_result.h
Go to the documentation of this file.
1 /* Copyright (C) 2012 and 2013 Chris Vine
2
3 The library comprised in this file or of which this file is part is
4 distributed by Chris Vine under the GNU Lesser General Public
5 License as follows:
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public License
9 as published by the Free Software Foundation; either version 2.1 of
10 the License, or (at your option) any later version.
11
12 This library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License, version 2.1, for more details.
16
17 You should have received a copy of the GNU Lesser General Public
18 License, version 2.1, along with this library (see the file LGPL.TXT
19 which came with this source code package in the c++-gtk-utils
20 sub-directory); if not, write to the Free Software Foundation, Inc.,
21 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22
23 However, it is not intended that the object code of a program whose
24 source code instantiates a template from this file or uses macros or
25 inline functions (of any length) should by reason only of that
26 instantiation or use be subject to the restrictions of use in the GNU
27 Lesser General Public License. With that in mind, the words "and
28 macros, inline functions and instantiations of templates (of any
29 length)" shall be treated as substituted for the words "and small
30 macros and small inline functions (ten lines or less in length)" in
31 the fourth paragraph of section 5 of that licence. This does not
32 affect any other reason why object code may be subject to the
33 restrictions in that licence (nor for the avoidance of doubt does it
34 affect the application of section 2 of that licence to modifications
35 of the source code in this file).
36
37 */
38
39 /**
40 * @file async_result.h
41 * @brief This file provides a thread-safe asynchronous result class.
42 */
43
44 #ifndef CGU_ASYNC_RESULT_H
45 #define CGU_ASYNC_RESULT_H
46
47 #include <utility> // for std::move
48
49 #include <c++-gtk-utils/mutex.h>
50 #include <c++-gtk-utils/thread.h>
51 #include <c++-gtk-utils/cgu_config.h>
52
53
54 namespace Cgu {
55
56 /**
57 * @class AsyncResult async_result.h c++-gtk-utils/async_result.h
58 * @brief A thread-safe asynchronous result class.
59 * @sa AsyncQueueDispatch Thread::Future
60 *
61 * Cgu::Thread::Future operates on the principle of there being one
62 * worker thread per task. In some cases however, it may be better to
63 * have a worker thread, or a limited pool of worker threads,
64 * executing a larger number of tasks. This can be implemented by
65 * having a worker thread or threads waiting on a
66 * Cgu::AsyncQueueDispatch object, onto which other threads push tasks
67 * represented by std::unique_ptr<const Cgu::Callback::Callback> or
68 * Cgu::Callback::SafeFunctor objects.
69 *
70 * Where this model is adopted, when a task completes it may report
71 * its results by dispatching a further callback to a glib main loop
72 * using Cgu::Callback::post(). However, there will also be cases
73 * where, rather than passing a result as an event to a main loop, a
74 * thread is to to wait for the task to complete. This class is
75 * intended to facilitate that. It operates in a way which is similar
76 * to the std::promise class in C++11. The thread which wishes to
77 * extract a result can call the get() method, which will block until
78 * the worker thread has called the set() method or posted an error.
79 *
80 * For safety reasons, the get() method returns by value and so will
81 * cause that value to be copied once. From version 2.0.11 a
82 * move_get() method is provided which will make a move operation
83 * instead of a copy if the value type implements a move constructor,
84 * but see the documentation on move_get() for the caveats with
85 * respect to its use: in particular, if move_get() is to be called by
86 * a thread, then get() may not be called by another thread.
87 *
88 * Here is a compilable example of a calculator class which runs a
89 * dedicated thread on which it carries out all its calculations:
90 *
91 * @code
92 * #include <vector>
93 * #include <numeric>
94 * #include <memory>
95 * #include <ostream>
96 * #include <iostream>
97 *
98 * #include <c++-gtk-utils/async_result.h>
99 * #include <c++-gtk-utils/async_queue.h>
100 * #include <c++-gtk-utils/shared_ptr.h>
101 * #include <c++-gtk-utils/thread.h>
102 * #include <c++-gtk-utils/callback.h>
103 *
104 * using namespace Cgu;
105 *
106 * class Calcs {
107 * AsyncQueueDispatch<std::unique_ptr<const Callback::Callback>> jobs;
108 * Thread::JoinableHandle t;
109 *
110 * void do_jobs() {
111 * for (;;) {
112 * std::unique_ptr<const Callback::Callback> job;
113 * jobs.move_pop_dispatch(job);
114 * job->dispatch();
115 * }
116 * }
117 * public:
118 *
119 * SharedLockPtr<AsyncResult<double>> mean(const std::vector<double>& nums) {
120 * SharedLockPtr<AsyncResult<double>> res(new AsyncResult<double>);
121 * jobs.emplace(Callback::lambda<>([=]() {
122 * if (nums.empty()) res->set(0.0);
123 * else res->set(std::accumulate(nums.begin(), nums.end(), 0.0)/nums.size());
124 * return;
125 * }));
126 * return res;
127 * }
128 *
129 * // ... other calculation methods here
130 *
131 * Calcs() {
132 * t = Thread::JoinableHandle(Thread::Thread::start(Callback::make(*this, &Calcs::do_jobs), true),
133 * Thread::JoinableHandle::join_on_exit);
134 * if (!t.is_managing()) throw "Thread start error";
135 * }
136 * ~Calcs() {
137 * jobs.emplace(Callback::lambda<>([]() {throw Thread::Exit();}));
138 * t.join();
139 * }
140 * };
141 *
142 * int main () {
143 *
144 * Calcs calcs;
145 * auto res1 = calcs.mean(std::vector<double>({1, 2, 8, 0}));
146 * auto res2 = calcs.mean(std::vector<double>({101, 53.7, 87, 1.2}));
147 *
148 * // ... do something else
149 *
150 * std::cout << res1->get() << std::endl;
151 * std::cout << res2->get() << std::endl;
152 *
153 * }
154 * @endcode
155 *
156 * AsyncResult objects cannot be copied by value, and as they need to
157 * be visible both to the set()ing and get()ing threads, it will often
158 * be easiest to construct them on free store and copy them by smart
159 * pointer, as in the example above. However, if the library is
160 * compiled with the \--with-glib-memory-slices-compat or
161 * \--with-glib-memory-slices-no-compat configuration options, any
162 * AsyncResult object constructed on free store will be constructed in
163 * glib memory slices, which are an efficient small object allocator.
164 */
165
166 template <class T> class AsyncResult {
167 T res;
168 bool done;
169 int error;
170 mutable Thread::Mutex mutex;
171 mutable Thread::Cond cond;
172
173 public:
174 /**
175 * @exception Thread::MutexError The constructor might throw this
176 * exception if initialisation of the contained mutex fails. (It is
177 * often not worth checking for this, as it means either memory is
178 * exhausted or pthread has run out of other resources to create new
179 * mutexes.) The constructor will also throw if the default
180 * constructor of the result type represented by this object throws.
181 * @exception Thread::CondError The constructor might throw this
182 * exception if initialisation of the contained condition variable
183 * fails. (It is often not worth checking for this, as it means
184 * either memory is exhausted or pthread has run out of other
185 * resources to create new condition variables.) The constructor will
186 * also throw if the default constructor of the result type
187 * represented by this object throws.
188 *
189 * Since 2.0.8
190 */
191 AsyncResult(): res(), done(false), error(0) {}
192
193 ~AsyncResult() {
194 // lock and unlock the mutex in the destructor so that we have an
195 // acquire operation to ensure that when this object is destroyed
196 // memory is synchronised, so any thread may destroy this object
197 Thread::Mutex::Lock lock{mutex};
198 }
199
200 // AsyncResult objects cannot be copied - they are mainly
201 // intended to pass a result between two known threads
202 /**
203 * This class cannot be copied. The copy constructor is deleted.
204 *
205 * Since 2.0.8
206 */
207 AsyncResult(const AsyncResult&) = delete;
208
209 /**
210 * This class cannot be copied. The assignment operator is deleted.
211 *
212 * Since 2.0.8
213 */
214 AsyncResult& operator=(const AsyncResult&) = delete;
215
216 /**
217 * This method sets the value represented by the AsyncResult object,
218 * provided that set() has not previously been called and
219 * set_error() has not previously been called with a value other
220 * than 0. If set() has previously been called or set_error()
221 * called with a value other than 0 (so that is_done() will return
222 * true) this method does nothing. It is thread safe. It is not a
223 * cancellation point. It will not throw unless the copy assignment
224 * operator of the value type throws.
225 * @param val The value which this object is to represent and which
226 * calls to get() or a call to move_get() will return. Any thread
227 * waiting on get() or move_get() will unblock, and any subsequent
228 * calls to is_done() will return true.
229 * @return true if the call to this method is effective because
230 * set() has not previously been called and set_error() has not
231 * previously been called with a value other than 0, otherwise
232 * false.
233 *
234 * Since 2.0.8
235 */
236 bool set(const T& val) {
237 Thread::Mutex::Lock lock{mutex};
238 if (!done) {
239 res = val;
240 done = true;
241 cond.broadcast();
242 return true;
243 }
244 return false;
245 }
246
247 /**
248 * This method sets the value represented by the AsyncResult object,
249 * provided that set() has not previously been called and
250 * set_error() has not previously been called with a value other
251 * than 0. If set() has previously been called or set_error()
252 * called with a value other than 0 (so that is_done() will return
253 * true) this method does nothing. It is thread safe. It is not a
254 * cancellation point. It will not throw unless the copy or move
255 * assignment operator of the value type throws.
256 * @param val The value which this object is to represent and which
257 * calls to get() or a call to move_get() will return. Any thread
258 * waiting on get() or move_get() will unblock, and any subsequent
259 * calls to is_done() will return true.
260 * @return true if the call to this method is effective because
261 * set() has not previously been called and set_error() has not
262 * previously been called with a value other than 0, otherwise
263 * false.
264 *
265 * Since 2.0.8
266 */
267 bool set(T&& val) {
268 Thread::Mutex::Lock lock{mutex};
269 if (!done) {
270 res = std::move(val);
271 done = true;
272 cond.broadcast();
273 return true;
274 }
275 return false;
276 }
277
278 /**
279 * This method gets the stored value represented by the AsyncResult
280 * object. It is thread safe. It is a cancellation point if it
281 * blocks, and is cancellation safe if the stack unwinds on
282 * cancellation. Any number of threads may call this method and
283 * block on it. It will not throw unless the copy constructor of
284 * the return type throws. It is strongly exception safe.
285 * @return the value represented by this object as set by a call to
286 * set(). If no such value has been set (and no error has been set)
287 * so that is_done() will return false, this method will block until
288 * either a value or an error has been set. If an error has been
289 * set, this method will return a default constructed object of the
290 * template type (and the error can be obtained with get_error()).
291 * @note Question: Couldn't this method return the stored value by
292 * lvalue reference to const? Answer: It could. However, because
293 * of return value optimization, which will be implemented by any
294 * compiler capable of compiling this library, no advantage would be
295 * gained by doing so when initializing a local variable with the
296 * return value of this method (the copy constructor will only be
297 * called once whether returning by value or const reference). The
298 * advantage of returning by value is that the call to the copy
299 * constructor is forced to be within the AsyncResult object's
300 * mutex, so different threads' calls to the copy constructor are
301 * serialized, and also with blocked cancellation, so this method is
302 * cancellation safe. All calls to this method by different threads
303 * are therefore isolated and we do not have to worry about the
304 * thread safety of direct access to the stored value via its const
305 * methods outside the mutex (which would not be thread safe if the
306 * stored value has data members declared mutable) nor about the
307 * cancellation safety of the copy constructor. Of course, for
308 * objects which do not have mutable data, a hit arises by returning
309 * by value in cases where it is not intended to initialize a local
310 * variable at all nor to cancel a thread: where, say, only const
311 * methods are to be called on the return value (which could be done
312 * directly if this method returned by const reference). However,
313 * in many use cases this will be mitigated by the move_get()
314 * method.
315 *
316 * Since 2.0.8
317 */
318 T get() const {
319 Thread::Mutex::Lock lock{mutex};
320 while (!done) cond.wait(mutex);
321 Thread::CancelBlock b;
322 return res;
323 }
324
325 /**
326 * This method gets the stored value represented by the AsyncResult
327 * object by a move operation, if the type of that value implements
328 * a move constructor (otherwise this method does the same as the
329 * get() method). It is provided as an option for cases where a
330 * move is required for efficiency reasons, but although it may be
331 * called by any thread, a move operation may normally only be made
332 * once (except where the return type has been designed to be moved
333 * more than once for the limited purpose of inspecting a flag
334 * indicating whether its value is valid or not). If this method is
335 * to be called then no calls to get() by another thread should
336 * normally be made. This method is a cancellation point if it
337 * blocks, and is cancellation safe if the stack unwinds on
338 * cancellation. It will not throw unless the copy or move
339 * constructor of the return type throws. It is only exception safe
340 * if the return type's move constructor is exception safe.
341 * @return The value represented by this object as set by a call to
342 * set(). If no such value has been set (and no error has been set)
343 * so that is_done() will return false, this method will block until
344 * either a value or an error has been set. If an error has been
345 * set, until a move operation has been carried out this method will
346 * return a default constructed object of the template type (and the
347 * error can be obtained with get_error()).
348 * @note Question: Couldn't this method return the stored value by
349 * rvalue reference? Answer: It could. However, because of return
350 * value optimization, which will be implemented by any compiler
351 * capable of compiling this library, no advantage would be gained
352 * by doing so when initializing a local variable with the return
353 * value of this method (the move constructor will only be called
354 * once, and no call will be made to the copy constructor, whether
355 * returning by value or rvalue reference). The advantage of
356 * returning by value is that the call to the move constructor is
357 * forced to be within the AsyncResult object's mutex, so different
358 * threads' calls to the move constructor are serialized, and also
359 * with blocked cancellation, so this method is cancellation safe.
360 * All calls to this method by different threads are therefore
361 * isolated and we do not have to worry about the thread safety of
362 * the mutating first call to this method, nor about direct access
363 * to the stored value via a rvalue reference outside the mutex nor
364 * the cancellation safety of the move constructor.
365 *
366 * Since 2.0.11
367 */
368 T move_get() {
369 Thread::Mutex::Lock lock{mutex};
370 while (!done) cond.wait(mutex);
371 Thread::CancelBlock b;
372 return std::move(res);
373 }
374
375 /**
376 * This method sets an error if called with a value other than 0,
377 * provided that set() has not previously been called and this
378 * method has not previously been called with a value other than 0.
379 * If set() has been called or this method previously called with a
380 * value other than 0 (so that is_done() will return true), this
381 * method does nothing. This method is thread safe. It is not a
382 * cancellation point. It will not throw.
383 * @param err The value which subsequent calls to get_error() will
384 * report. If the value of err is 0, or if this method has been
385 * called with a value other than 0 or set() has previously been
386 * called, this method will do nothing. Otherwise, any thread
387 * waiting on get() or move_get() will unblock (they will return a
388 * default constructed object of the template type), and any
389 * subsequent calls to is_done() will return true.
390 * @return true if the call to this method is effective because the
391 * error value passed is not 0, set() has not previously been called
392 * and this method has not previously been called with a value other
393 * than 0, otherwise false.
394 *
395 * Since 2.0.8
396 */
397 bool set_error(int err = -1) {
398 Thread::Mutex::Lock lock{mutex};
399 if (err && !done) {
400 error = err;
401 done = true;
402 cond.broadcast();
403 return true;
404 }
405 return false;
406 }
407
408 /**
409 * This method is thread safe. It is not a cancellation point. It
410 * will not throw.
411 * @return the error value set by a call to set_error(), or 0 if no
412 * error has been set.
413 *
414 * Since 2.0.8
415 */
416 int get_error() const {
417 Thread::Mutex::Lock lock{mutex};
418 return error;
419 }
420
421 /**
422 * This method is thread safe. It is not a cancellation point. It
423 * will not throw.
424 * @return true if set() has been called, or set_error() has been
425 * called with a value other than 0, otherwise false.
426 *
427 * Since 2.0.8
428 */
429 bool is_done() const {
430 Thread::Mutex::Lock lock{mutex};
431 return done;
432 }
433
434 /* Only has effect if --with-glib-memory-slices-compat or
435 * --with-glib-memory-slices-no-compat option picked */
436 CGU_GLIB_MEMORY_SLICES_FUNCS
437 };
438
439 } // namespace Cgu
440
441 #endif