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