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