c++-gtk-utils
future.h
Go to the documentation of this file.
1 /* Copyright (C) 2010 to 2012 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 src/utils sub-directory);
20  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 #ifndef CGU_FUTURE_H
40 #define CGU_FUTURE_H
41 
42 #include <memory>
43 #include <exception>
44 #include <functional> // for std::function
45 #include <utility> // for std::move and std::forward
46 
47 #include <pthread.h>
48 #include <glib.h>
49 
50 #include <c++-gtk-utils/thread.h>
51 #include <c++-gtk-utils/mutex.h>
52 #include <c++-gtk-utils/callback.h>
55 #include <c++-gtk-utils/emitter.h>
56 #include <c++-gtk-utils/timeout.h>
58 
59 namespace Cgu {
60 
61 namespace Thread {
62 
63 struct FutureThreadError: public std::exception {
64  virtual const char* what() const throw() {return "FutureThreadError\n";}
65 };
66 
67 struct FutureWhenError: public std::exception {
68  virtual const char* what() const throw() {return "FutureWhenError\n";}
69 };
70 
71 /**
72  * @class Cgu::Thread::Future future.h c++-gtk-utils/future.h
73  * @brief A class representing a pthread thread which will
74  * provide a value.
75  * @sa Cgu::Thread::Thread Cgu::Thread::JoinableHandle Cgu::AsyncResult Cgu::Thread::make_future()
76  *
77  * The Thread::Future class will launch a worker thread, run the
78  * function it represents in that thread until it returns, and store
79  * the return value so that it can be waited on and/or extracted by
80  * another thread. A new Thread::Future object representing the
81  * function to be called is created by calling
82  * Cgu::Thread::Future<>::make() (a static member function) or from
83  * version 2.0.4 the Cgu::Thread::make_future() helper function. The
84  * worker thread is then started by calling run(), and the value
85  * extracted or waited for by calling get(). The run() method can
86  * only be called once, but any number of threads can wait for and/or
87  * extract the return value by calling the get() method. The class
88  * also provides a SafeEmitter @ref DoneEmitterAnchor "done_emitter"
89  * public object which emits when the worker thread has finished, and
90  * an associated when() function. In addition, from version 2.0.11 a
91  * move_get() method is provided, which is discussed further below.
92  *
93  * The template parameter type of Thread::Future is the type of the
94  * return value of the function called by the Thread::Future object.
95  * The return value can be any type, including any arbitrarily large
96  * tuple or other struct or standard C++ container (but see below
97  * about copying).
98  *
99  * A Thread::Future object cannot represent a function with a void
100  * return type - a compilation error will result if that is attempted.
101  * If no return value is wanted, then the Thread::Thread class can be
102  * used directly. (However, if in a particular usage this class is
103  * thought to be more convenient, the function to be represented by it
104  * can be wrapped by another function which provides a dummy return
105  * value, such as a dummy int. One possible case for this is where
106  * more than one thread wants to wait for the worker thread to
107  * terminate, as pthread_join() and so Thread::Thread::join() only
108  * give defined behaviour when called by one thread.) In addition, a
109  * Thread::Future object cannot represent a function with a non-const
110  * reference argument - that would not normally be safe, and a compile
111  * error will be generated if that is attempted. However, from
112  * version 2.0.0-rc3, const reference arguments can be bound to
113  * Thread::Future objects (this is safe, as the Thread::Future object
114  * will keep its own copy of the argument passed to it).
115  *
116  * The make() method and make_future() functions take a plain
117  * function, static member function or non-static member function,
118  * which can take up to three arguments in the case of a non-static
119  * member function, and four arguments in the case of any other
120  * function. In the case of a non-static member function, the
121  * referenced object whose member function is to be called must remain
122  * in existence until the worker thread has completed. Alternatively,
123  * a std::function object can be passed, which can have any number of
124  * arguments using std::bind (and which can also bind the referenced
125  * object of a non-static member function by taking a copy of it where
126  * that is necessary).
127  *
128  * Where a std::function object is not passed, internal moving/copying
129  * of arguments for the target function to be represented by the
130  * Thread::Future object takes place (once by invoking the rvalue move
131  * constructor or lvalue copy constructor, as appropriate, when make()
132  * or make_future() are called and, if the argument is not a const
133  * reference argument, once in the worker thread when run() is
134  * called). Therefore, if a non-trivial class object is to be
135  * received by the target function as an argument, it is best either
136  * (a) if it has a rvalue constructor, to pass it to make() or
137  * make_future() as a temporary and have the target function take a
138  * const reference argument, or (b) for it to be constructed on free
139  * store and for the target function to receive it by pointer, by
140  * Cgu::SharedLockPtr, or by a std::shared_ptr implementation which
141  * has a thread-safe reference count. Note also that constructing
142  * std::function objects using std::bind can cause a number of copies
143  * of arguments to be made, so for ordinary usage it is better to pass
144  * a function pointer with arguments to make() or make_future() rather
145  * than a std::function object.
146  *
147  * Copying of the return value of the target function represented by
148  * the Thread::Future object also takes place. The run() method will
149  * store the return value of that function, so that it is available to
150  * the get() and move_get() methods and any 'when' callback, and
151  * therefore copy it once (unless, that is, the target function's
152  * return value type has a move assignment operator, in which case
153  * where possible that operator is called).
154  *
155  * For safety reasons, the get() method returns by value and so will
156  * cause the return value to be copied once more, so for return values
157  * comprising complex class objects which are to be abstracted using
158  * the get() method, it is often better if the function represented by
159  * the Thread::Future object allocates the return value on free store
160  * and returns it by pointer, by Cgu::SharedLockPtr, or by a
161  * std::shared_ptr implementation which has a thread-safe reference
162  * count. Alternatively, from version 2.0.11 a move_get() method is
163  * provided which will attempt a move operation instead of a copy, but
164  * see the documentation on move_get() for the caveats with respect to
165  * its use: in particular, if move_get() is to be called by a thread,
166  * then get() may not normally be called by another thread, nor should
167  * the when() method be called.
168  *
169  * It should be noted that where the when() method is used, the return
170  * value is passed to the 'when' callback by reference to const and so
171  * without the copying carried out by the get() method: therefore, if
172  * the return value has a move assignment operator and the when()
173  * method is to be employed, and the 'when' callback only needs to
174  * call const methods of the return value, it may be more efficient
175  * not to allocate the return value on free store.
176  *
177  * This is a usage example:
178  *
179  * @code
180  * class Numbers {
181  * public:
182  * std::vector<long> get_primes(int n); // calculates the first n primes
183  * // and puts them in a vector
184  * ...
185  * };
186  *
187  * Numbers obj;
188  *
189  * // get the first 1,000 primes
190  * using namespace Cgu;
191  *
192  * auto future = Thread::make_future(obj, &Numbers::get_primes, 1000);
193  * // Thread::make_future() is a wrapper for the equivalent long-hand version required prior to version 2.0.4:
194  * // auto future = Thread::Future<std::vector<long>>::make(obj, &Numbers::get_primes, 1000);
195  *
196  * future->run();
197  * ... [ do something else ] ...
198  * std::vector<long> result(future->move_get());
199  * std::for_each(result.begin(), result.end(), [](long l) {std::cout << l << std::endl;});
200  * @endcode
201  *
202  * If get_primes() were a static member function or plain function,
203  * the syntax would be:
204  *
205  * @code
206  * auto future = Thread::make_future(&Numbers::get_primes, 1000);
207  * @endcode
208  *
209  * @b The @b Cgu::Thread::Future::when() @b functions
210  *
211  * From version 2.0.2, the return value of the thread function
212  * represented by Cgu::Thread::Future can be obtained asynchronously
213  * using Cgu::Thread::Future::when() to execute a function in a glib
214  * main loop when the thread function completes. The above example
215  * could be reimplemented as:
216  *
217  * @code
218  * class Numbers {
219  * public:
220  * std::vector<long> get_primes(int n); // calculates the first n primes
221  * // and puts them in a vector
222  * ...
223  * };
224  *
225  * void print_primes(const std::vector<long>& result) {
226  * std::for_each(result.begin(), result.end(), [](long l) {std::cout << l << std::endl;});
227  * }
228  *
229  * Numbers obj;
230  *
231  * using namespace Cgu;
232  *
233  * auto future = Thread::make_future(obj, &Numbers::get_primes, 1000);
234  * future->when(Callback::make(&print_primes));
235  * future->run();
236  * @endcode
237  *
238  * In this example, the callback which prints the primes to the
239  * console would execute in the default program main loop once the
240  * thread function providing those primes returns. As an alternative
241  * to a free standing print_primes() function, the callback object
242  * could be constructed from a C++11 lambda expression using
243  * Cgu::Callback::lambda() (available from version 2.0.9).
244  *
245  * @b Lambda @b functions
246  *
247  * As mentioned above, Cgu::Thread::Future objects can be constructed
248  * from std::function objects. Because C++11 lambda expressions are
249  * implicitly convertible to std::function objects and the only type
250  * to be resolved by the Cgu::Thread::Future::make() and
251  * Cgu::Thread::make_future() factory functions for such objects is
252  * the return type, this means that those functions can be passed a
253  * lambda expression, as for example:
254  *
255  * @code
256  * using namespace Cgu;
257  * int i = 1;
258  * auto f = Thread::Future<int>::make([=]() {return i + 10;});
259  * f->run();
260  * std::cout << f->get() << std::endl;
261  * @endcode
262  *
263  * However, if make_future() is used, the return type parameter must
264  * be explicitly stated:
265  *
266  * @code
267  * using namespace Cgu;
268  * int i = 1;
269  * auto f = Thread::make_future<int>([=]() {return i + 10;});
270  * f->run();
271  * std::cout << f->get() << std::endl;
272  * @endcode
273  *
274  * Lambda expressions which do not capture a variable from their
275  * environment are also convertible to a function pointer, but in the
276  * absence of an explicit cast the conversion to std::function object
277  * will be preferred.
278  *
279  * @b Overloaded @b functions
280  *
281  * Where a member function or ordinary function represented by a
282  * Thread::Future object is overloaded, this will cause difficulties
283  * in template type deduction when Thread::Future<>::make() or
284  * Thread::make_future() are called. With Thread::Future<>::make(),
285  * functions may be overloaded on numbers of argument without
286  * difficulty, but not with Thread::make_future(). For example:
287  * @code
288  * class Numbers {
289  * public:
290  * int calc(int i);
291  * int calc(int i, int j);
292  * ...
293  * };
294  *
295  * Numbers obj;
296  *
297  * using namespace Cgu;
298  *
299  * int i = 1, j = 2;
300  *
301  * auto f1 =
302  * Thread::Future<int>::make(obj, &Numbers::calc, i); // OK
303  * auto f2 =
304  * Thread::Future<int>::make(obj, &Numbers::calc, i, j); // OK
305  *
306  * // explicit is disambiguation required with Thread::make_future()
307  * auto f3 =
308  * Thread::make_future(obj, static_cast<int(Numbers::*)(int)>(&Numbers::calc), i);
309  * auto f4 =
310  * Thread::make_future(obj, static_cast<int(Numbers::*)(int, int)>(&Numbers::calc), i, j);
311  * @endcode
312  * Neither Thread::Future<>::make() nor Thread::make_future() can be
313  * overloaded on types of argument without explicit disambiguation.
314  * For example:
315  * @code
316  * class Numbers {
317  * public:
318  * int calc(int i);
319  * int calc(double d);
320  * ...
321  * };
322  *
323  * Numbers obj;
324  *
325  * using namespace Cgu;
326  *
327  * int i = 1;
328  * double d = 2.0;
329  *
330  * auto f1 =
331  * Thread::Future<int>::make(obj, static_cast<int (Numbers::*)(int)>(&Numbers::calc), i);
332  * auto f2 =
333  * Thread::Future<int>::make(obj, static_cast<int (Numbers::*)(double)>(&Numbers::calc), d);
334  * auto f3 =
335  * Thread::make_future(obj, static_cast<int (Numbers::*)(int)>(&Numbers::calc), i);
336  * auto f4 =
337  * Thread::make_future(obj, static_cast<int (Numbers::*)(double)>(&Numbers::calc), d);
338  * @endcode
339  */
340 
341 template <class Val>
343 
344  std::unique_ptr<Cgu::Thread::Thread> thread_u;
345  std::unique_ptr<Cgu::Callback::Callback> cb_u;
346 
347  mutable Mutex mutex;
348  Cond cond;
349  Val val;
350  bool done;
351  bool running;
352  bool error;
353  bool emitter_error;
354 
355  template <class T, class Ret, class... Args>
356  void run_wrapper(T*, Ret (T::*)(Args...), const Args&...);
357 
358  template <class T, class Ret, class... Args>
359  void run_wrapper_const(const T*, Ret (T::*)(Args...) const, const Args&...);
360 
361  template <class Ret, class... Args>
362  void run_wrapper_static(Ret (*)(Args...), const Args&...);
363 
364  void run_wrapper_func(const std::function<Val(void)>&);
365 
366  void cancel_cleanup();
367 
368  void execute_done(const Cgu::Callback::SafeFunctorArg<const Val&>&);
369  void post_done(const Cgu::Callback::SafeFunctorArg<const Val&>&,
370  gint, GMainContext*);
371  void execute_done_rel(const Cgu::SharedLockPtr<Cgu::SafeEmitterArg<const Val&>>&);
372  void post_done_rel(const Cgu::SharedLockPtr<Cgu::SafeEmitterArg<const Val&>>&,
373  gint, GMainContext*);
374 
375  // this is a static function taking the future object by IntrusivePtr to
376  // ensure that the future object remains in existence whilst this
377  // function might execute
378  static void fail_cb(const Cgu::IntrusivePtr<Future<Val>>& future,
379  const Cgu::Callback::SafeFunctor& func,
380  bool& ret);
381 
382  // private constructor - this class can only be created with Thread::Future::make()
383  Future(): val(), done(false), running(false), error(false), emitter_error(false) {}
384 
385 public:
386 
387  // this class cannot be copied except by smart pointer
388 /**
389  * This class cannot be copied (except by smart pointer). The copy
390  * constructor is deleted.
391  */
392  Future(const Future&) = delete;
393 
394 /**
395  * This class cannot be copied (except by smart pointer). The
396  * assignment operator is deleted.
397  */
398  Future& operator=(const Future&) = delete;
399 
400 /**
401  * Constructs a new Cgu::Thread::Future object (returned by
402  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
403  * Val represents the return value of the function to be represented
404  * by the new object. From version 2.0.4, it will usually be more
405  * convenient to call the Cgu::Thread::make_future() function, which
406  * is a convenience wrapper for this static method.
407  * @exception std::bad_alloc It might throw std::bad_alloc if memory
408  * is exhausted and the system throws in that case. (This exception
409  * will not be thrown if the library has been installed using the
410  * --with-glib-memory-slices-no-compat configuration option: instead
411  * glib will terminate the program if it is unable to obtain memory
412  * from the operating system.) It will also throw if the default
413  * constructor of the return value type throws.
414  */
415  template <class Ret, class T>
417  Ret (T::*func)());
418 
419 /**
420  * Constructs a new Cgu::Thread::Future object (returned by
421  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
422  * Val represents the return value of the function to be represented
423  * by the new object. From version 2.0.4, it will usually be more
424  * convenient to call the Cgu::Thread::make_future() function, which
425  * is a convenience wrapper for this static method.
426  * @exception std::bad_alloc It might throw std::bad_alloc if memory
427  * is exhausted and the system throws in that case. (This exception
428  * will not be thrown if the library has been installed using the
429  * --with-glib-memory-slices-no-compat configuration option: instead
430  * glib will terminate the program if it is unable to obtain memory
431  * from the operating system.) It will also throw if the copy
432  * constructor or assignment operator of the bound argument throws, or
433  * the default constructor of the return value type throws.
434  */
435  template <class Ret, class Param1, class Arg1, class T>
437  Ret (T::*func)(Param1),
438  Arg1&& arg1);
439 
440 /**
441  * Constructs a new Cgu::Thread::Future object (returned by
442  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
443  * Val represents the return value of the function to be represented
444  * by the new object. From version 2.0.4, it will usually be more
445  * convenient to call the Cgu::Thread::make_future() function, which
446  * is a convenience wrapper for this static method.
447  * @exception std::bad_alloc It might throw std::bad_alloc if memory
448  * is exhausted and the system throws in that case. (This exception
449  * will not be thrown if the library has been installed using the
450  * --with-glib-memory-slices-no-compat configuration option: instead
451  * glib will terminate the program if it is unable to obtain memory
452  * from the operating system.) It will also throw if the copy
453  * constructor or assignment operator of a bound argument throws, or
454  * the default constructor of the return value type throws.
455  */
456  template <class Ret, class Param1, class Param2, class Arg1, class Arg2, class T>
458  Ret (T::*func)(Param1, Param2),
459  Arg1&& arg1,
460  Arg2&& arg2);
461 
462 /**
463  * Constructs a new Cgu::Thread::Future object (returned by
464  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
465  * Val represents the return value of the function to be represented
466  * by the new object. From version 2.0.4, it will usually be more
467  * convenient to call the Cgu::Thread::make_future() function, which
468  * is a convenience wrapper for this static method.
469  * @exception std::bad_alloc It might throw std::bad_alloc if memory
470  * is exhausted and the system throws in that case. (This exception
471  * will not be thrown if the library has been installed using the
472  * --with-glib-memory-slices-no-compat configuration option: instead
473  * glib will terminate the program if it is unable to obtain memory
474  * from the operating system.) It will also throw if the copy
475  * constructor or assignment operator of a bound argument throws, or
476  * the default constructor of the return value type throws.
477  */
478  template <class Ret, class Param1, class Param2, class Param3,
479  class Arg1, class Arg2, class Arg3, class T>
481  Ret (T::*func)(Param1, Param2, Param3),
482  Arg1&& arg1,
483  Arg2&& arg2,
484  Arg3&& arg3);
485 
486 /**
487  * Constructs a new Cgu::Thread::Future object (returned by
488  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
489  * Val represents the return value of the function to be represented
490  * by the new object. From version 2.0.4, it will usually be more
491  * convenient to call the Cgu::Thread::make_future() function, which
492  * is a convenience wrapper for this static method.
493  * @exception std::bad_alloc It might throw std::bad_alloc if memory
494  * is exhausted and the system throws in that case. (This exception
495  * will not be thrown if the library has been installed using the
496  * --with-glib-memory-slices-no-compat configuration option: instead
497  * glib will terminate the program if it is unable to obtain memory
498  * from the operating system.) It will also throw if the default
499  * constructor of the return value type throws.
500  */
501  template <class Ret, class T>
503  Ret (T::*func)() const);
504 
505 /**
506  * Constructs a new Cgu::Thread::Future object (returned by
507  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
508  * Val represents the return value of the function to be represented
509  * by the new object. From version 2.0.4, it will usually be more
510  * convenient to call the Cgu::Thread::make_future() function, which
511  * is a convenience wrapper for this static method.
512  * @exception std::bad_alloc It might throw std::bad_alloc if memory
513  * is exhausted and the system throws in that case. (This exception
514  * will not be thrown if the library has been installed using the
515  * --with-glib-memory-slices-no-compat configuration option: instead
516  * glib will terminate the program if it is unable to obtain memory
517  * from the operating system.) It will also throw if the copy
518  * constructor or assignment operator of the bound argument throws, or
519  * the default constructor of the return value type throws.
520  */
521  template <class Ret, class Param1, class Arg1, class T>
523  Ret (T::*func)(Param1) const,
524  Arg1&& arg1);
525 
526 /**
527  * Constructs a new Cgu::Thread::Future object (returned by
528  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
529  * Val represents the return value of the function to be represented
530  * by the new object. From version 2.0.4, it will usually be more
531  * convenient to call the Cgu::Thread::make_future() function, which
532  * is a convenience wrapper for this static method.
533  * @exception std::bad_alloc It might throw std::bad_alloc if memory
534  * is exhausted and the system throws in that case. (This exception
535  * will not be thrown if the library has been installed using the
536  * --with-glib-memory-slices-no-compat configuration option: instead
537  * glib will terminate the program if it is unable to obtain memory
538  * from the operating system.) It will also throw if the copy
539  * constructor or assignment operator of a bound argument throws, or
540  * the default constructor of the return value type throws.
541  */
542  template <class Ret, class Param1, class Param2, class Arg1, class Arg2, class T>
544  Ret (T::*func)(Param1, Param2) const,
545  Arg1&& arg1,
546  Arg2&& arg2);
547 
548 /**
549  * Constructs a new Cgu::Thread::Future object (returned by
550  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
551  * Val represents the return value of the function to be represented
552  * by the new object. From version 2.0.4, it will usually be more
553  * convenient to call the Cgu::Thread::make_future() function, which
554  * is a convenience wrapper for this static method.
555  * @exception std::bad_alloc It might throw std::bad_alloc if memory
556  * is exhausted and the system throws in that case. (This exception
557  * will not be thrown if the library has been installed using the
558  * --with-glib-memory-slices-no-compat configuration option: instead
559  * glib will terminate the program if it is unable to obtain memory
560  * from the operating system.) It will also throw if the copy
561  * constructor or assignment operator of a bound argument throws, or
562  * the default constructor of the return value type throws.
563  */
564  template <class Ret, class Param1, class Param2, class Param3,
565  class Arg1, class Arg2, class Arg3, class T>
567  Ret (T::*func)(Param1, Param2, Param3) const,
568  Arg1&& arg1,
569  Arg2&& arg2,
570  Arg3&& arg3);
571 
572 /**
573  * Constructs a new Cgu::Thread::Future object (returned by
574  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
575  * Val represents the return value of the function to be represented
576  * by the new object. From version 2.0.4, it will usually be more
577  * convenient to call the Cgu::Thread::make_future() function, which
578  * is a convenience wrapper for this static method.
579  * @exception std::bad_alloc It might throw std::bad_alloc if memory
580  * is exhausted and the system throws in that case. (This exception
581  * will not be thrown if the library has been installed using the
582  * --with-glib-memory-slices-no-compat configuration option: instead
583  * glib will terminate the program if it is unable to obtain memory
584  * from the operating system.) It will also throw if the default
585  * constructor of the return value type throws.
586  */
587  template <class Ret>
588  static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)());
589 
590 /**
591  * Constructs a new Cgu::Thread::Future object (returned by
592  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
593  * Val represents the return value of the function to be represented
594  * by the new object. From version 2.0.4, it will usually be more
595  * convenient to call the Cgu::Thread::make_future() function, which
596  * is a convenience wrapper for this static method.
597  * @exception std::bad_alloc It might throw std::bad_alloc if memory
598  * is exhausted and the system throws in that case. (This exception
599  * will not be thrown if the library has been installed using the
600  * --with-glib-memory-slices-no-compat configuration option: instead
601  * glib will terminate the program if it is unable to obtain memory
602  * from the operating system.) It will also throw if the copy
603  * constructor or assignment operator of the bound argument throws, or
604  * the default constructor of the return value type throws.
605  */
606  template <class Ret, class Param1, class Arg1>
607  static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)(Param1),
608  Arg1&& arg1);
609 
610 /**
611  * Constructs a new Cgu::Thread::Future object (returned by
612  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
613  * Val represents the return value of the function to be represented
614  * by the new object. From version 2.0.4, it will usually be more
615  * convenient to call the Cgu::Thread::make_future() function, which
616  * is a convenience wrapper for this static method.
617  * @exception std::bad_alloc It might throw std::bad_alloc if memory
618  * is exhausted and the system throws in that case. (This exception
619  * will not be thrown if the library has been installed using the
620  * --with-glib-memory-slices-no-compat configuration option: instead
621  * glib will terminate the program if it is unable to obtain memory
622  * from the operating system.) It will also throw if the copy
623  * constructor or assignment operator of a bound argument throws, or
624  * the default constructor of the return value type throws.
625  */
626  template <class Ret, class Param1, class Param2, class Arg1, class Arg2>
627  static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)(Param1, Param2),
628  Arg1&& arg1,
629  Arg2&& arg2);
630 
631 /**
632  * Constructs a new Cgu::Thread::Future object (returned by
633  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
634  * Val represents the return value of the function to be represented
635  * by the new object. From version 2.0.4, it will usually be more
636  * convenient to call the Cgu::Thread::make_future() function, which
637  * is a convenience wrapper for this static method.
638  * @exception std::bad_alloc It might throw std::bad_alloc if memory
639  * is exhausted and the system throws in that case. (This exception
640  * will not be thrown if the library has been installed using the
641  * --with-glib-memory-slices-no-compat configuration option: instead
642  * glib will terminate the program if it is unable to obtain memory
643  * from the operating system.) It will also throw if the copy
644  * constructor or assignment operator of a bound argument throws, or
645  * the default constructor of the return value type throws.
646  */
647  template <class Ret, class Param1, class Param2, class Param3,
648  class Arg1, class Arg2, class Arg3>
649  static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)(Param1, Param2, Param3),
650  Arg1&& arg1,
651  Arg2&& arg2,
652  Arg3&& arg3);
653 
654 /**
655  * Constructs a new Cgu::Thread::Future object (returned by
656  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
657  * Val represents the return value of the function to be represented
658  * by the new object. From version 2.0.4, it will usually be more
659  * convenient to call the Cgu::Thread::make_future() function, which
660  * is a convenience wrapper for this static method.
661  * @exception std::bad_alloc It might throw std::bad_alloc if memory
662  * is exhausted and the system throws in that case. (This exception
663  * will not be thrown if the library has been installed using the
664  * --with-glib-memory-slices-no-compat configuration option: instead
665  * glib will terminate the program if it is unable to obtain memory
666  * from the operating system.) It will also throw if the copy
667  * constructor or assignment operator of a bound argument throws, or
668  * the default constructor of the return value type throws.
669  */
670  template <class Ret, class Param1, class Param2, class Param3, class Param4,
671  class Arg1, class Arg2, class Arg3, class Arg4>
672  static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)(Param1, Param2, Param3, Param4),
673  Arg1&& arg1,
674  Arg2&& arg2,
675  Arg3&& arg3,
676  Arg4&& arg4);
677 
678 /**
679  * Constructs a new Cgu::Thread::Future object (returned by
680  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
681  * Val represents the return value of the function to be represented
682  * by the new object. From version 2.0.4, it will usually be more
683  * convenient to call the Cgu::Thread::make_future() function, which
684  * is a convenience wrapper for this static method.
685  * @exception std::bad_alloc It might throw std::bad_alloc if memory
686  * is exhausted and the system throws in that case. (This exception
687  * will not be thrown if the library has been installed using the
688  * --with-glib-memory-slices-no-compat configuration option: instead
689  * glib will terminate the program if it is unable to obtain memory
690  * from the operating system.) It will also throw if the copy
691  * constructor or assignment operator of a bound argument throws, or
692  * the default constructor of the return value type throws.
693  */
694  static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(const std::function<Val(void)>& func);
695 
696 /**
697  * Constructs a new Cgu::Thread::Future object (returned by
698  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>). The type parameter
699  * Val represents the return value of the function to be represented
700  * by the new object. From version 2.0.4, it will usually be more
701  * convenient to call the Cgu::Thread::make_future() function, which
702  * is a convenience wrapper for this static method.
703  * @exception std::bad_alloc It might throw std::bad_alloc if memory
704  * is exhausted and the system throws in that case. (This exception
705  * will not be thrown if the library has been installed using the
706  * --with-glib-memory-slices-no-compat configuration option: instead
707  * glib will terminate the program if it is unable to obtain memory
708  * from the operating system.) It will also throw if the copy
709  * constructor or assignment operator of a bound argument throws, or
710  * the default constructor of the return value type throws.
711  */
712  static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(std::function<Val(void)>&& func);
713 
714 /**
715  * Runs the function represented by this Cgu::Thread::Future object in
716  * a new worker thread. That function will only be run once. If this
717  * is the first time this method has been called, it will start the
718  * worker thread and return true, and if it has previously been
719  * called, this method will do nothing and return false. This method
720  * is thread safe and may be called by a different thread from the one
721  * which called make().
722  * @return true if this is the first time this method has been called,
723  * or false if this method has previously been called.
724  * @exception Cgu::Thread::FutureThreadError This method might throw
725  * Cgu::Thread::FutureThreadError if it has not previously been called
726  * and the thread did not start properly. If it does throw, this
727  * Cgu::Thread::Future object is defunct and further attempts to call
728  * this method will return immediately with a false value. (It is
729  * often not worth checking for this exception, as it means either
730  * memory is exhausted, the pthread thread limit has been reached or
731  * pthread has run out of other resources to start new threads.)
732  * @exception std::bad_alloc This method might throw std::bad_alloc if
733  * it has not previously been called, and memory is exhausted and the
734  * system throws in that case. If it does throw, this
735  * Cgu::Thread::Future object is defunct and further attempts to call
736  * this method will return immediately with a false value. (This
737  * exception will not be thrown if the library has been installed
738  * using the --with-glib-memory-slices-no-compat configuration option:
739  * instead glib will terminate the program if it is unable to obtain
740  * memory from the operating system.)
741  * @note 1. Any Cgu::Thread::Exit exception, or any uncaught exception
742  * derived from std::exception, which is thrown from the worker thread
743  * will be caught and consumed and the error flag will be set. The
744  * worker thread will safely terminate and unwind the stack in so
745  * doing.
746  * @note 2. As this wrapper class can provide error reporting in a way
747  * that Cgu::Thread::Thread of itself cannot, it would be desirable to
748  * consume any other uncaught exceptions. However, this cannot be
749  * done: annoyingly, NPTL's forced stack unwinding does not allow this
750  * if thread cancellation is to be made available. If an uncaught
751  * exception propagates out of a thread when the thread exits, the
752  * C++11 standard will cause std::terminate() to be called and so
753  * terminate the entire program. Accordingly, a user must make sure
754  * that no exceptions, other than Cgu::Thread::Exit or those derived
755  * from std::exception or any cancellation pseudo-exception, can
756  * propagate from the function which this Cgu::Thread::Future object
757  * represents.
758  * @note 3. If the worker thread is cancelled by a call to cancel()
759  * while in the middle of executing the function which this
760  * Cgu::Thread::Future object represents, the error flag will be set.
761  */
762  bool run();
763 
764 /**
765  * Gets the stored value obtained from the function which is
766  * represented by this object. If the worker thread launched by the
767  * call to run() has not completed, then this method will block until
768  * it has completed. If run() has not been called, then run() will be
769  * called (and this method will block until the launched worker thread
770  * completes). If the function which is represented by this object
771  * throws Cgu::Thread::Exit or an uncaught exception derived from
772  * std::exception, then the exception will have been consumed by this
773  * Cgu::Thread::Future object and the error flag will have been set.
774  * The error flag will also have been set if the worker thread is
775  * cancelled or the thread wrapper in this Cgu::Thread::Future object
776  * threw std::bad_alloc. This method is thread safe and may be called
777  * by any thread (and by more than one thread). It is a cancellation
778  * point if it blocks, and from version 2.0.11 is cancellation safe if
779  * the stack unwinds on cancellation. It is also strongly exception
780  * safe: no data will be lost if extracting the value fails.
781  * @return The value obtained from the function which is represented
782  * by this object
783  * @exception Cgu::Thread::FutureThreadError This method might throw
784  * Cgu::Thread::FutureThreadError if run() has not previously been
785  * called and the thread did not start properly when this function
786  * called run().
787  * @exception std::bad_alloc This method might throw std::bad_alloc if
788  * run() has not previously been called, memory is exhausted and the
789  * system throws in that case. (This exception will not be thrown if
790  * the library has been installed using the
791  * --with-glib-memory-slices-no-compat configuration option: instead
792  * glib will terminate the program if it is unable to obtain memory
793  * from the operating system.)
794  * @note This method might also throw if the copy constructor of the
795  * returned value type throws.
796  */
797  Val get();
798 
799 /**
800  * Gets the stored value obtained from the function which is
801  * represented by this object by a move operation, if the return type
802  * implements a move constructor (otherwise this method does the same
803  * as the get() method). It is provided as an option for cases where
804  * a move is required for efficiency reasons, but although it may be
805  * called by any thread, a move from this Thread::Future object may
806  * normally only be made once (except where the return type has been
807  * designed to be moved more than once for the limited purpose of
808  * inspecting a flag indicating whether its value is valid or not).
809  * If this method is to be called then no calls to get() by another
810  * thread should normally be made and no calls to when() should be
811  * made. If the worker thread launched by the call to run() has not
812  * completed, then this method will block until it has completed. If
813  * run() has not been called, then run() will be called (and this
814  * method will block until the launched worker thread completes). If
815  * the function which is represented by this object throws
816  * Cgu::Thread::Exit or an uncaught exception derived from
817  * std::exception, then the exception will have been consumed by this
818  * Cgu::Thread::Future object and the error flag will have been set.
819  * The error flag will also have been set if the worker thread is
820  * cancelled or the thread wrapper in this Cgu::Thread::Future object
821  * threw std::bad_alloc. This method is a cancellation point if it
822  * blocks, and is cancellation safe if the stack unwinds on
823  * cancellation. This method is only exception safe if the return
824  * type's move constructor is exception safe.
825  * @return The value obtained from the function which is represented
826  * by this object
827  * @exception Cgu::Thread::FutureThreadError This method might throw
828  * Cgu::Thread::FutureThreadError if run() has not previously been
829  * called and the thread did not start properly when this function
830  * called run().
831  * @exception std::bad_alloc This method might throw std::bad_alloc if
832  * run() has not previously been called, memory is exhausted and the
833  * system throws in that case. (This exception will not be thrown if
834  * the library has been installed using the
835  * --with-glib-memory-slices-no-compat configuration option: instead
836  * glib will terminate the program if it is unable to obtain memory
837  * from the operating system.)
838  * @note This method might also throw if the copy or move constructor
839  * of the returned value type throws.
840  *
841  * Since 2.0.11
842  */
843  Val move_get();
844 
845 /**
846  * Cancels the worker thread in which the function represented by this
847  * object runs, if that function has not yet finished. If this method
848  * is called and the worker thread is still running and is cancelled
849  * in response to a call to this method, then the error flag will be
850  * set so that a method calling get() or move_get() can examine
851  * whether the result is valid. If run() has not yet been called or
852  * the worker thread has already finished executing the function
853  * represented by this object then this function does nothing and
854  * returns false. This method is thread safe and may be called by any
855  * thread. It will not throw.
856  * @return true if run() has previously been called and the worker
857  * thread has not yet finished executing the function represented by
858  * this object, otherwise false (in which case this method does
859  * nothing).
860  * @note 1. Use this method with care. When cancelling a thread not
861  * all thread implementations will unwind the stack, and so run the
862  * destructors of local objects. This is discussed further in the
863  * documentation on Cgu::Thread::Thread::cancel().
864  * @note 2. This method might return true because the worker thread
865  * has not yet finished, but the error flag might still not be set.
866  * This is because the worker thread may not meet a cancellation point
867  * before it ends naturally. It is the error flag which indicates
868  * definitively whether the worker thread terminated prematurely in
869  * response to a call to this method.
870  */
871  bool cancel();
872 
873 /**
874  * A utility enabling the value returned by the thread function
875  * represented by this Cgu::Thread::Future object to be dealt with
876  * asynchronously rather than by (or in addition to) a call to the
877  * get() method. It causes the callback passed as an argument to this
878  * method (referred to below as the 'when' callback) to be executed by
879  * a thread's main loop if and when the thread function represented by
880  * this Cgu::Thread::Future object finishes correctly - the 'when'
881  * callback is passed that thread function's return value when it is
882  * invoked. This method is thread safe, and may be called by any
883  * thread.
884  *
885  * This functionality is implemented by connecting an internal
886  * dispatching callback to the done_emitter object.
887  *
888  * The 'when' callback should take a single unbound argument
889  * comprising a const reference to the return type of the thread
890  * function represented by this Cgu::Thread::Future object. (So, in
891  * the case of a Future<int> object, the callback function should take
892  * a const int& argument as the unbound argument.) The 'when'
893  * callback can have any number of bound arguments, except that a
894  * bound argument may not include a copy of this Cgu::Thread::Future
895  * object held by intrusive pointer as returned by the make() methods
896  * (that would result in this Cgu::Thread::Future object owning, via
897  * done_emitter, a reference to itself and so become incapable of
898  * being freed). The 'when' callback may, however, take a pointer to
899  * this Cgu::Thread::Future object, as obtained by the
900  * Cgu::IntrusivePtr::get() method, because this Cgu::Thread::Future
901  * object is guaranteed to remain in existence until the callback has
902  * completed executing.
903  *
904  * This method cannot be called after the thread function represented
905  * by this Cgu::Thread::Future object has completed (either
906  * successfully or unsuccessfully) so that is_done() would return
907  * true, and if this is attempted a Cgu::Thread::FutureWhenError
908  * exception will be thrown. Therefore, generally this method should
909  * be called before the run() method has been called.
910  *
911  * Once the run() method has been called, this Cgu::Thread::Future
912  * object will always stay in existence until the thread function
913  * represented by it has completed (whether correctly, by cancellation
914  * or by a thrown exception), and any 'when' callback (and any other
915  * callbacks connected to the done_emitter object) and any 'fail'
916  * callback have completed. Accordingly it is safe to use this method
917  * even if the intrusive pointer object returned by the make() methods
918  * will go out of scope before the 'when' callback has executed: the
919  * callback will execute correctly irrespective of that.
920  *
921  * Summary: use of this method is safe and has been implemented in a
922  * way which does not give rise to timing issues.
923  *
924  * If memory is exhausted and std::bad_alloc is thrown by the thread
925  * wrapper of Cgu::Thread::Future after run() is called or by
926  * done_emitter when emitting, or if the thread function represented
927  * by this Cgu::Thread::Future object throws Cgu::Thread::Exit, exits
928  * with an uncaught exception deriving from std::exception or is
929  * cancelled, or if the copy constructor of a non-reference bound
930  * argument of the 'when' callback throws, or any other callback has
931  * been connected to done_emitter before this method is called which
932  * exits with an uncaught exception, then the 'when' callback will not
933  * execute (instead the exception concerned will be consumed and an
934  * error indicated). With many systems, swap memory combined with
935  * memory over-commit makes it pointless to check for std::bad_alloc
936  * (and even more so in programs using glib, as glib aborts a program
937  * where it cannot obtain memory from the operating system). So
938  * subject to that, if the user program is designed so that the thread
939  * function represented by this Cgu::Thread::Future object does not
940  * exit with uncaught exceptions, does not throw Cgu::Thread::Exit and
941  * is not cancelled, and so that the 'when' callback does not exit
942  * with an uncaught exception and either has no non-reference bound
943  * arguments or the copy constructors of any non-reference bound
944  * arguments do not throw, and if this method is called before any
945  * other callbacks are connected to done_emitter, the possibility of
946  * failure can be disregarded.
947  *
948  * In cases where that is not true and detecting whether a failure has
949  * occurred is required, a fail() method is provided. It should be
950  * noted that a callback handed to the fail() method will not execute
951  * in a case of error if the error comprises the 'when' callback
952  * exiting with an uncaught exception when it is executed by the main
953  * loop, or the copy constructor of one of its non-reference bound
954  * arguments throwing when it executes (such an exception would be
955  * consumed internally in order to protect the main loop and a
956  * g_critical message issued). If the 'when' callback might exit with
957  * an uncaught exception when executing or have the copy constructor
958  * of a non-reference bound argument throw, and doing something other
959  * than consuming the exception and issuing a g_critical message is
960  * required, then a different approach is to start a new thread to
961  * wait on the get() method which can act on the result of is_error()
962  * directly.
963  *
964  * If glib < 2.32 is used, the glib main loop must have been made
965  * thread-safe by a call to g_thread_init() before this function is
966  * called. glib >= 2.32 does not require g_thread_init() to be called
967  * in order to be thread safe.
968  *
969  * @param cb The 'when' callback (the callback to be executed when the
970  * function represented by this Cgu::Thread::Future object has
971  * successfully completed). Ownership is taken of this object, and it
972  * will be deleted when it has been finished with.
973  * @param priority The priority to be given to the 'when' callback in
974  * the main loop after the thread function represented by this
975  * Cgu::Thread::Future object has successfully completed. In
976  * ascending order of priorities, priorities are G_PRIORITY_LOW,
977  * G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT
978  * and G_PRIORITY_HIGH. The default is G_PRIORITY_DEFAULT. This
979  * determines the order in which the callback will appear in the event
980  * list in the main loop, not the priority which the OS will adopt.
981  * @param context The glib main context of the thread in whose main
982  * loop the 'when' callback is to be executed (the default of NULL
983  * will cause the callback to be executed in the main program loop).
984  * @return The internal dispatching callback created by this method
985  * and connected to done_emitter. It is made available as a return
986  * value so that if wanted it can be disconnected programmatically
987  * from done_emitter, or block()/unblock() can be called on it (but if
988  * that is to be done, it must be done before the thread function
989  * represented by this Cgu::Thread::Future object has completed in
990  * order for it to be effective).
991  * @exception Cgu::Thread::FutureWhenError This method will throw
992  * Cgu::Thread::FutureWhenError if it is called after the thread
993  * function represented by this Cgu::Thread::Future object has
994  * completed. If it does so, the 'when' callback will be disposed of.
995  * @exception std::bad_alloc This method might throw std::bad_alloc if
996  * memory is exhausted and the system throws in that case. If it does
997  * so, the 'when' callback will be disposed of.
998  * @note The return value of the function represented by this
999  * Cgu::Thread::Future object is stored and passed as an argument to
1000  * the 'when' callback by const reference. If other threads might
1001  * concurrently call this object's get() method, which copies the
1002  * stored value, the stored type's copy constructor must be thread
1003  * safe with respect to the stored type's const methods. This would
1004  * be relevant if the stored type has data members declared mutable
1005  * which would be copied by its copy constructor.
1006  *
1007  * Since 2.0.2
1008  */
1010  gint priority = G_PRIORITY_DEFAULT,
1011  GMainContext* context = 0);
1012 
1013 /**
1014  * This is a version of the utility enabling the value returned by the
1015  * thread function represented by this Cgu::Thread::Future object to
1016  * be dealt with asynchronously, which takes a Releaser object for
1017  * automatic disconnection of the callback passed as an argument to
1018  * this method (referred to below as the 'when' callback), if the
1019  * object having the 'when' callback function as a member is
1020  * destroyed. For this to be race free, the lifetime of that object
1021  * must be controlled by the thread in whose main loop the 'when'
1022  * callback will execute.
1023  *
1024  * If the 'when' callback has not been released, this method causes it
1025  * to be executed by a thread's main loop if and when the thread
1026  * function represented by this Cgu::Thread::Future object finishes
1027  * correctly - the 'when' callback is passed that thread function's
1028  * return value when it is invoked. This method is thread safe, and
1029  * may be called by any thread.
1030  *
1031  * This functionality is implemented by connecting an internal
1032  * dispatching callback to the done_emitter object.
1033  *
1034  * The 'when' callback should take a single unbound argument
1035  * comprising a const reference to the return type of the thread
1036  * function represented by this Cgu::Thread::Future object. (So, in
1037  * the case of a Future<int> object, the callback function should take
1038  * a const int& argument as the unbound argument.) The 'when'
1039  * callback can have any number of bound arguments, except that a
1040  * bound argument may not include a copy of this Cgu::Thread::Future
1041  * object held by intrusive pointer as returned by the make() methods
1042  * (that would result in this Cgu::Thread::Future object owning, via
1043  * done_emitter, a reference to itself and so become incapable of
1044  * being freed). The 'when' callback may, however, take a pointer to
1045  * this Cgu::Thread::Future object, as obtained by the
1046  * Cgu::IntrusivePtr::get() method, because this Cgu::Thread::Future
1047  * object is guaranteed to remain in existence until the callback has
1048  * completed executing.
1049  *
1050  * This method cannot be called after the thread function represented
1051  * by this Cgu::Thread::Future object has completed (either
1052  * successfully or unsuccessfully) so that is_done() would return
1053  * true, and if this is attempted a Cgu::Thread::FutureWhenError
1054  * exception will be thrown. Therefore, generally this method should
1055  * be called before the run() method has been called.
1056  *
1057  * The documentation for the version of this method which does not
1058  * take a Releaser object gives further details of how this method is
1059  * used.
1060  *
1061  * If glib < 2.32 is used, the glib main loop must have been made
1062  * thread-safe by a call to g_thread_init() before this function is
1063  * called. glib >= 2.32 does not require g_thread_init() to be called
1064  * in order to be thread safe.
1065  *
1066  * @param cb The 'when' callback (the callback to be executed when the
1067  * function represented by this Cgu::Thread::Future object has
1068  * successfully completed). Ownership is taken of this object, and it
1069  * will be deleted when it has been finished with.
1070  * @param r A Releaser object for automatic disconnection of the
1071  * 'when' callback if the object of which the callback function is a
1072  * member is destroyed.
1073  * @param priority The priority to be given to the 'when' callback in
1074  * the main loop after the thread function represented by this
1075  * Cgu::Thread::Future object has successfully completed. In
1076  * ascending order of priorities, priorities are G_PRIORITY_LOW,
1077  * G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT
1078  * and G_PRIORITY_HIGH. The default is G_PRIORITY_DEFAULT. This
1079  * determines the order in which the callback will appear in the event
1080  * list in the main loop, not the priority which the OS will adopt.
1081  * @param context The glib main context of the thread in whose main
1082  * loop the 'when' callback is to be executed (the default of NULL
1083  * will cause the callback to be executed in the main program loop).
1084  * @return The internal dispatching callback created by this method
1085  * and connected to done_emitter. It is made available as a return
1086  * value so that if wanted it can be disconnected programmatically
1087  * from done_emitter, or block()/unblock() can be called on it (but if
1088  * that is to be done, it must be done before the thread function
1089  * represented by this Cgu::Thread::Future object has completed in
1090  * order for it to be effective).
1091  * @exception Cgu::Thread::FutureWhenError This method will throw
1092  * Cgu::Thread::FutureWhenError if it is called after the thread
1093  * function represented by this Cgu::Thread::Future object has
1094  * completed. If it does so, the 'when' callback will be disposed of.
1095  * @exception std::bad_alloc This method might throw std::bad_alloc if
1096  * memory is exhausted and the system throws in that case. If it does
1097  * so, the 'when' callback will be disposed of.
1098  * @exception Cgu::Thread::MutexError This method will throw
1099  * Cgu:Thread::MutexError if initialisation of the mutex in a
1100  * SafeEmitterArg object constructed by this method fails. If it does
1101  * so, the 'when' callback will be disposed of. (It is often not
1102  * worth checking for this, as it means either memory is exhausted or
1103  * pthread has run out of other resources to create new mutexes.)
1104  * @note The return value of the function represented by this
1105  * Cgu::Thread::Future object is stored and passed as an argument to
1106  * the 'when' callback by const reference. If other threads might
1107  * concurrently call this object's get() method, which copies the
1108  * stored value, the stored type's copy constructor must be thread
1109  * safe with respect to the stored type's const methods. This would
1110  * be relevant if the stored type has data members declared mutable
1111  * which would be copied by its copy constructor.
1112  *
1113  * Since 2.0.2
1114  */
1116  Cgu::Releaser& r,
1117  gint priority = G_PRIORITY_DEFAULT,
1118  GMainContext* context = 0);
1119 
1120 /**
1121  * A utility intended to be used where relevant in conjunction with
1122  * the when() methods. It enables a callback to be executed in a glib
1123  * main loop (referred to below as the 'fail' callback) if memory is
1124  * exhausted and std::bad_alloc was thrown by the thread wrapper of
1125  * Cgu::Thread::Future after calling run() or by done_emitter when
1126  * emitting, or if the thread function represented by this
1127  * Cgu::Thread::Future object threw Cgu::Thread::Exit, exited with an
1128  * uncaught exception deriving from std::exception or was cancelled,
1129  * or any callback connected to done_emitter exited with an uncaught
1130  * exception. It therefore enables errors to be detected and acted on
1131  * without having a thread wait on the get() method in order to test
1132  * is_error() or is_emitter_error().
1133  *
1134  * It is implemented by attaching a timeout to the main loop which
1135  * polls at 100 millisecond intervals and tests is_done()/is_error()
1136  * and is_emitter_done()/is_emitter_error(). The timeout is
1137  * automatically removed by the implementation once it has been
1138  * detected that an error has occurred and the 'fail' callback is
1139  * executed, or if the thread function represented by this Cgu::Future
1140  * object and all done_emitter emissions (including execution of any
1141  * 'when' callback) have completed successfully.
1142  *
1143  * This method can be called before or after the run() method has been
1144  * called, and whether or not the thread function represented by this
1145  * Cgu::Thread::Future object has completed.
1146  *
1147  * Once this method has been called, this Cgu::Thread::Future object
1148  * will always stay in existence until the timeout has been
1149  * automatically removed by the implementation. Accordingly it is
1150  * safe to use this method even if the intrusive pointer object
1151  * returned by the make() methods will go out of scope before the
1152  * 'fail' callback has executed: the callback will execute correctly
1153  * irrespective of that.
1154  *
1155  * This method does not have a priority argument: as a polling timeout
1156  * is created, a particular priority will normally have no
1157  * significance (in fact, the 'fail' callback will execute in the main
1158  * loop with a priority of G_PRIORITY_DEFAULT). If in a special case
1159  * a different polling interval than 100 milliseconds or a different
1160  * priority is required, users can attach their own polling timeouts
1161  * to a main loop and carry out the tests by hand.
1162  *
1163  * Four other points should be noted. First, if as well as the when()
1164  * method being called some other callback has been connected to
1165  * done_emitter, and that other callback throws, the 'fail' callback
1166  * will execute. Therefore, if the particular program design requires
1167  * that the 'fail' callback should only execute if the 'when' callback
1168  * is not executed (and the 'when' callback only execute if the 'fail'
1169  * callback does not execute), no other callbacks which throw should
1170  * be connected to done_emitter.
1171  *
1172  * Secondly, as mentioned in the documentation on the when() method,
1173  * if the 'when' callback exits with an uncaught exception upon being
1174  * executed by the main loop or has a non-reference bound argument
1175  * whose copy constructor throws when it executes, the 'fail' callback
1176  * will not execute (the exception will have been consumed internally
1177  * in order to protect the main loop and a g_critical message issued).
1178  *
1179  * Thirdly, avoid if possible having the 'fail' callback represent a
1180  * function which might throw or which has a non-reference bound
1181  * argument whose copy constructor might throw (such an exception
1182  * would be consumed internally in order to protect the main loop and
1183  * a g_critical message issued, but no other error indication apart
1184  * from the g_critical message will be provided).
1185  *
1186  * Fourthly, unlike the 'when' callback, a copy of this
1187  * Cgu::Thread::Future object held by intrusive pointer as returned by
1188  * the make() methods may safely be bound to the 'fail' callback,
1189  * which would enable the 'fail' callback to determine whether it is
1190  * is_error() or is_emitter_error() which returns false.
1191  *
1192  * If glib < 2.32 is used, the glib main loop must have been made
1193  * thread-safe by a call to g_thread_init() before this function is
1194  * called. glib >= 2.32 does not require g_thread_init() to be called
1195  * in order to be thread safe.
1196  *
1197  * @param cb The 'fail' callback (the callback to be executed if the
1198  * thread function represented by this Cgu::Thread::Future object or a
1199  * done_emitter emission has failed to complete). Ownership is taken
1200  * of this object, and it will be deleted when it has been finished
1201  * with.
1202  * @param context The glib main context of the thread in whose main
1203  * loop the 'fail' callback is to be executed (the default of NULL
1204  * will cause the functor to be executed in the main program loop).
1205  * @exception std::bad_alloc This method might throw std::bad_alloc if
1206  * memory is exhausted and the system throws in that case. If it does
1207  * so, the 'fail' callback will be disposed of.
1208  *
1209  * Since 2.0.2
1210  */
1211  void fail(const Cgu::Callback::Callback* cb,
1212  GMainContext* context = 0);
1213 
1214 /**
1215  * This is a version of the fail() utility for use in conjunction with
1216  * the when() methods, which takes a Releaser object for automatic
1217  * disconnection of the callback functor passed as an argument to this
1218  * method if the object having the callback function as a member is
1219  * destroyed.
1220  *
1221  * This method enables a callback to be executed in a glib main loop
1222  * if memory is exhausted and std::bad_alloc was thrown by the thread
1223  * wrapper of Cgu::Thread::Future after calling run() or by
1224  * done_emitter when emitting, or if the thread function represented
1225  * by this Cgu::Thread::Future object threw Cgu::Thread::Exit, exited
1226  * with an uncaught exception deriving from std::exception or was
1227  * cancelled, or any callback connected to done_emitter exited with an
1228  * uncaught exception. It therefore enables errors to be detected and
1229  * acted on without having a thread wait on the get() method in order
1230  * to test is_error() or is_emitter_error().
1231  *
1232  * This method can be called before or after the run() method has been
1233  * called, and whether or not the thread function represented by this
1234  * Cgu::Thread::Future object has completed.
1235  *
1236  * The documentation for the version of this method which does not
1237  * take a Releaser object gives further details of how this method is
1238  * used.
1239  *
1240  * If glib < 2.32 is used, the glib main loop must have been made
1241  * thread-safe by a call to g_thread_init() before this function is
1242  * called. glib >= 2.32 does not require g_thread_init() to be called
1243  * in order to be thread safe.
1244  *
1245  * @param cb The 'fail' callback (the callback to be executed if the
1246  * thread function represented by this Cgu::Thread::Future object or a
1247  * done_emitter emission has failed to complete). Ownership is taken
1248  * of this object, and it will be deleted when it has been finished
1249  * with.
1250  * @param r A Releaser object for automatic disconnection of the
1251  * 'fail' callback if the object of which the callback function is a
1252  * member is destroyed.
1253  * @param context The glib main context of the thread in whose main
1254  * loop the 'fail' callback is to be executed (the default of NULL
1255  * will cause the functor to be executed in the main program loop).
1256  * @exception std::bad_alloc This method might throw std::bad_alloc if
1257  * memory is exhausted and the system throws in that case. If it does
1258  * so, the 'fail' callback will be disposed of.
1259  * @exception Cgu::Thread::MutexError This method will throw
1260  * Cgu:Thread::MutexError if initialisation of the mutex in a
1261  * SafeEmitterArg object constructed by Cgu::start_timeout() fails.
1262  * If it does so, the 'fail' callback will be disposed of. (It is
1263  * often not worth checking for this, as it means either memory is
1264  * exhausted or pthread has run out of other resources to create new
1265  * mutexes.)
1266  *
1267  * Since 2.0.2
1268  */
1269  void fail(const Cgu::Callback::Callback* cb,
1270  Cgu::Releaser& r,
1271  GMainContext* context = 0);
1272 
1273 /**
1274  * @return true if the function represented by this
1275  * Cgu::Thread::Future object has finished, either by returning
1276  * normally, by cancellation or by virtue of having thrown
1277  * Cgu::Thread::Exit or some exception derived from std::exception.
1278  * Once this method returns true, then it is guaranteed that the get()
1279  * or move_get() method will not block (except as incidental to any
1280  * contention between threads calling get()). Once this method has
1281  * returned true or get() or move_get() has unblocked, then the result
1282  * of is_error() is definitive. This method is thread safe and may be
1283  * called by any thread. It will not throw.
1284  * @note This method will return true even though any callbacks
1285  * connected to done_emitter are still executing or waiting to
1286  * execute. From version 2.0.2 the is_emitter_done() method will
1287  * indicate when done_emitter callbacks (if any) have also completed.
1288  */
1289  bool is_done() const;
1290 
1291 /**
1292  * @return true if both the function represented by this
1293  * Cgu::Thread::Future object has finished and any callbacks connected
1294  * to done_emitter have completed. Once this method returns true,
1295  * then the result of is_emitter_error() is definitive. This method
1296  * is thread safe and may be called by any thread. It will not throw.
1297  * @note This method will return true automatically if is_error() and
1298  * is_done() return true, because if the function represented by this
1299  * Cgu::Thread::Future object was cancelled or exited with an uncaught
1300  * exception, done_emitter is never emitted. In addition, if this
1301  * method returns true, then is_done() must also return true.
1302  *
1303  * Since 2.0.2
1304  */
1305  bool is_emitter_done() const;
1306 
1307 /**
1308  * @return true if (a) a Cgu::Thread::Exit exception has been thrown
1309  * by the function represented by this Cgu::Thread::Future object
1310  * (which will have been consumed by this Cgu::Thread::Future object),
1311  * (b) an exception derived from std::exception has been thrown by
1312  * that function which was not caught in that function (and which will
1313  * also have been consumed by this Cgu::Thread::Future object), (c)
1314  * the worker thread in which that function runs was cancelled in
1315  * mid-course with a call to cancel() or (d) the thread wrapper
1316  * implementing the worker thread in this Cgu::Thread::Future object
1317  * threw and then consumed std::bad_alloc (this is different from the
1318  * run() method throwing std::bad_alloc). In these cases the value
1319  * obtained by get() or move_get() will not be valid (it will be a
1320  * default constructed object of the return type of the function
1321  * represented by this Cgu::Thread::Future object). Otherwise this
1322  * method returns false. The result of this method is definitive once
1323  * get() or move_get() has unblocked or is_done() returns true. This
1324  * method is thread safe and may be called by any thread. It will not
1325  * throw.
1326  */
1327  bool is_error() const;
1328 
1329 /**
1330  * @return true if an uncaught exception arose in emitting @ref
1331  * DoneEmitterAnchor "done_emitter" when executing callbacks connected
1332  * to it. Otherwise this method returns false. The result of this
1333  * method is definitive once is_emitter_done() returns true. This
1334  * method is thread safe and may be called by any thread. It will not
1335  * throw.
1336  * @note This method will return false automatically if is_error()
1337  * returns true, because if the function represented by this
1338  * Cgu::Thread::Future object was cancelled or exited with an uncaught
1339  * exception, done_emitter is never emitted. It follows that if this
1340  * method returns true, is_error() must return false.
1341  */
1342  bool is_emitter_error() const;
1343 
1344 /**
1345  * A Cgu::SafeEmitter object which is emitted when the function
1346  * represented by this Cgu::Thread::Future object finishes correctly
1347  * (that is, the function is not cancelled and does not throw any
1348  * uncaught exceptions). By itself it does not do too much as it is
1349  * emitted (and connected callbacks execute in) the same worker thread
1350  * immediately after the Future function has completed. However, any
1351  * thread can connect a Callback object to this Cgu::SafeEmitter
1352  * object and a connected callback can, say, cause another Callback to
1353  * be executed in a thread's main loop using Cgu::Callback::post(),
1354  * and from version 2.0.2 when() methods are provided which will do
1355  * this for users automatically. Once the run() method has been
1356  * called, this Cgu::Thread::Future object (and so done_emitter) will
1357  * always stay in existence until the function represented by it has
1358  * completed (whether correctly, by cancellation or by a thrown
1359  * exception) and any callbacks connected to the done_emitter object
1360  * have completed, irrespective of whether the intrusive pointer
1361  * returned by the make() methods has gone out of scope.
1362  * @note 1. Cancellation is blocked while the Cgu::SafeEmitter object
1363  * emits and any connected callback executes.
1364  * @note 2. A connected callback can however terminate the worker
1365  * thread by throwing Cgu::Thread::Exit (in which case no subsequent
1366  * callbacks to be executed on that emission will execute either: the
1367  * worker thread will safely terminate and unwind the stack in so
1368  * doing). In that event, the emitter_error flag will be set.
1369  * @note 3. All other uncaught exceptions which might be thrown by the
1370  * Cgu::SafeEmitter object emitting, or by a connected callback
1371  * function executing, are consumed to retain the integrity of the
1372  * Thread::Future object. In the event of such an exception being
1373  * thrown, the emitter_error flag will be set. In summary, the
1374  * emitter_error flag will be set if (a) a callback function throws
1375  * Cgu::Thread::Exit, (b) some other uncaught exception escapes from a
1376  * callback function or (c) Cgu::SafeEmitter::emit() throws
1377  * std::bad_alloc or the copy constructor of a bound argument which is
1378  * not a reference argument has thrown. If the user knows that the
1379  * callback function does not throw Cgu::Thread::Exit and does not
1380  * allow any other exception to escape, then the cause must be a
1381  * std::bad_alloc memory exception in Cgu::SafeEmitter::emit() or the
1382  * copy constructor of a non-reference bound argument throwing.
1383  * @note 4. An emission is thread safe if the connected callback
1384  * functions are thread safe.
1385  * @note 5. This Cgu::Thread::Future object's mutex is released while
1386  * the Cgu::SafeEmitter object emits. This means that any connected
1387  * callbacks can safely call, say, the Future object's get() or
1388  * is_error() methods. However, a connected callback should not have
1389  * a bound argument comprising a copy of this Cgu::Thread::Future
1390  * object held by intrusive pointer as returned by the make() methods
1391  * (that would result in this Cgu::Thread::Future object owning, via
1392  * done_emitter, a reference to itself and so become incapable of
1393  * being freed). The callback may, however, take a pointer to this
1394  * Cgu::Thread::Future object as a bound argument, as obtained by the
1395  * Cgu::IntrusivePtr::get() method, because this Cgu::Thread::Future
1396  * object is guaranteed to remain in existence until all callbacks
1397  * connected to done_emitter have completed executing.
1398  * @anchor DoneEmitterAnchor
1399  */
1401 
1402 /* Only has effect if --with-glib-memory-slices-compat or
1403  * --with-glib-memory-slices-no-compat option picked */
1405 };
1406 
1407 /**
1408  * A convenience helper function which calls
1409  * Cgu::Thread::Future::make() to obtain a Future object without the
1410  * need to specify the return value of the function represented by the
1411  * new object: that is deduced from the signature of that function.
1412  * This is useful shorthand when also employed with the C++11 'auto'
1413  * keyword.
1414  * @exception std::bad_alloc It might throw std::bad_alloc if memory
1415  * is exhausted and the system throws in that case. (This exception
1416  * will not be thrown if the library has been installed using the
1417  * --with-glib-memory-slices-no-compat configuration option: instead
1418  * glib will terminate the program if it is unable to obtain memory
1419  * from the operating system.) It will also throw if the copy
1420  * constructor or assignment operator of a bound argument throws, or
1421  * the default constructor of the return value type of the function
1422  * represented by the new object throws.
1423  *
1424  * Since 2.0.4
1425  */
1426 template <class Obj, class Ret, class... Params, class... Args>
1428  Ret (Obj::*func)(Params...),
1429  Args&&... args) {
1430  return Cgu::Thread::Future<Ret>::make(obj, func, std::forward<Args>(args)...);
1431 }
1432 
1433 /**
1434  * A convenience helper function which calls
1435  * Cgu::Thread::Future::make() to obtain a Future object without the
1436  * need to specify the return value of the function represented by the
1437  * new object: that is deduced from the signature of that function.
1438  * This is useful shorthand when also employed with the C++11 'auto'
1439  * keyword.
1440  * @exception std::bad_alloc It might throw std::bad_alloc if memory
1441  * is exhausted and the system throws in that case. (This exception
1442  * will not be thrown if the library has been installed using the
1443  * --with-glib-memory-slices-no-compat configuration option: instead
1444  * glib will terminate the program if it is unable to obtain memory
1445  * from the operating system.) It will also throw if the copy
1446  * constructor or assignment operator of a bound argument throws, or
1447  * the default constructor of the return value type of the function
1448  * represented by the new object throws.
1449  *
1450  * Since 2.0.4
1451  */
1452 template <class Obj, class Ret, class... Params, class... Args>
1454  Ret (Obj::*func)(Params...) const,
1455  Args&&... args) {
1456  return Cgu::Thread::Future<Ret>::make(obj, func, std::forward<Args>(args)...);
1457 }
1458 
1459 /**
1460  * A convenience helper function which calls
1461  * Cgu::Thread::Future::make() to obtain a Future object without the
1462  * need to specify the return value of the function represented by the
1463  * new object: that is deduced from the signature of that function.
1464  * This is useful shorthand when also employed with the C++11 'auto'
1465  * keyword.
1466  * @exception std::bad_alloc It might throw std::bad_alloc if memory
1467  * is exhausted and the system throws in that case. (This exception
1468  * will not be thrown if the library has been installed using the
1469  * --with-glib-memory-slices-no-compat configuration option: instead
1470  * glib will terminate the program if it is unable to obtain memory
1471  * from the operating system.) It will also throw if the copy
1472  * constructor or assignment operator of a bound argument throws, or
1473  * the default constructor of the return value type of the function
1474  * represented by the new object throws.
1475  *
1476  * Since 2.0.4
1477  */
1478 template <class Ret, class... Params, class... Args>
1480  Args&&... args) {
1481  return Cgu::Thread::Future<Ret>::make(func, std::forward<Args>(args)...);
1482 }
1483 
1484 /**
1485  * A convenience helper function which calls
1486  * Cgu::Thread::Future::make() to obtain a Future object without the
1487  * need to specify the return value of the function represented by the
1488  * new object: that is deduced from the signature of that function.
1489  * This is useful shorthand when also employed with the C++11 'auto'
1490  * keyword.
1491  * @exception std::bad_alloc It might throw std::bad_alloc if memory
1492  * is exhausted and the system throws in that case. (This exception
1493  * will not be thrown if the library has been installed using the
1494  * --with-glib-memory-slices-no-compat configuration option: instead
1495  * glib will terminate the program if it is unable to obtain memory
1496  * from the operating system.) It will also throw if the copy
1497  * constructor or assignment operator of a bound argument throws, or
1498  * the default constructor of the return value type of the function
1499  * represented by the new object throws.
1500  *
1501  * Since 2.0.4
1502  */
1503 template <class Ret>
1504 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(const std::function<Ret(void)>& func) {
1505  return Cgu::Thread::Future<Ret>::make(func);
1506 }
1507 
1508 /**
1509  * A convenience helper function which calls
1510  * Cgu::Thread::Future::make() to obtain a Future object without the
1511  * need to specify the return value of the function represented by the
1512  * new object: that is deduced from the signature of that function.
1513  * This is useful shorthand when also employed with the C++11 'auto'
1514  * keyword.
1515  * @exception std::bad_alloc It might throw std::bad_alloc if memory
1516  * is exhausted and the system throws in that case. (This exception
1517  * will not be thrown if the library has been installed using the
1518  * --with-glib-memory-slices-no-compat configuration option: instead
1519  * glib will terminate the program if it is unable to obtain memory
1520  * from the operating system.) It will also throw if the copy
1521  * constructor or assignment operator of a bound argument throws, or
1522  * the default constructor of the return value type of the function
1523  * represented by the new object throws.
1524  *
1525  * Since 2.0.4
1526  */
1527 template <class Ret>
1528 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(std::function<Ret(void)>&& func) {
1529  return Cgu::Thread::Future<Ret>::make(std::move(func));
1530 }
1531 
1532 } // namespace Thread
1533 
1534 } // namespace Cgu
1535 
1536 #include <c++-gtk-utils/future.tpp>
1537 
1538 #endif