c++-gtk-utils
future.h
Go to the documentation of this file.
00001 /* Copyright (C) 2010 and 2011 Chris Vine
00002 
00003 The library comprised in this file or of which this file is part is
00004 distributed by Chris Vine under the GNU Lesser General Public
00005 License as follows:
00006 
00007    This library is free software; you can redistribute it and/or
00008    modify it under the terms of the GNU Lesser General Public License
00009    as published by the Free Software Foundation; either version 2.1 of
00010    the License, or (at your option) any later version.
00011 
00012    This library is distributed in the hope that it will be useful, but
00013    WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015    Lesser General Public License, version 2.1, for more details.
00016 
00017    You should have received a copy of the GNU Lesser General Public
00018    License, version 2.1, along with this library (see the file LGPL.TXT
00019    which came with this source code package in the src/utils sub-directory);
00020    if not, write to the Free Software Foundation, Inc.,
00021    59 Temple Place - Suite 330, Boston, MA, 02111-1307, USA.
00022 
00023 However, it is not intended that the object code of a program whose
00024 source code instantiates a template from this file or uses macros or
00025 inline functions (of any length) should by reason only of that
00026 instantiation or use be subject to the restrictions of use in the GNU
00027 Lesser General Public License.  With that in mind, the words "and
00028 macros, inline functions and instantiations of templates (of any
00029 length)" shall be treated as substituted for the words "and small
00030 macros and small inline functions (ten lines or less in length)" in
00031 the fourth paragraph of section 5 of that licence.  This does not
00032 affect any other reason why object code may be subject to the
00033 restrictions in that licence (nor for the avoidance of doubt does it
00034 affect the application of section 2 of that licence to modifications
00035 of the source code in this file).
00036 
00037 */
00038 
00039 #ifndef CGU_FUTURE_H
00040 #define CGU_FUTURE_H
00041 
00042 #include <memory>
00043 #include <exception>
00044 #include <functional> // for std::function
00045 #include <utility>    // for std::move and std::forward
00046 
00047 #include <pthread.h>
00048 #include <glib.h>
00049 
00050 #include <c++-gtk-utils/thread.h>
00051 #include <c++-gtk-utils/mutex.h>
00052 #include <c++-gtk-utils/callback.h>
00053 #include <c++-gtk-utils/intrusive_ptr.h>
00054 #include <c++-gtk-utils/shared_ptr.h>
00055 #include <c++-gtk-utils/emitter.h>
00056 #include <c++-gtk-utils/timeout.h>
00057 #include <c++-gtk-utils/cgu_config.h>
00058 
00059 namespace Cgu {
00060 
00061 namespace Thread {
00062 
00063 struct FutureThreadError: public std::exception {
00064   virtual const char* what() const throw() {return "FutureThreadError\n";}
00065 };
00066 
00067 struct FutureWhenError: public std::exception {
00068   virtual const char* what() const throw() {return "FutureWhenError\n";}
00069 };
00070 
00071 /**
00072  * @class Cgu::Thread::Future future.h c++-gtk-utils/future.h
00073  * @brief A class representing a pthread thread which will
00074  * provide a value.
00075  * @sa Cgu::Thread::Thread Cgu::Thread::JoinableHandle Cgu::Thread::make_future()
00076  *
00077  * The Thread::Future class will launch a worker thread, run the
00078  * function it represents in that thread until it returns, and store
00079  * the return value so that it can be waited on and/or extracted by
00080  * another thread.  A new Thread::Future object representing the
00081  * function to be called is created by calling
00082  * Cgu::Thread::Future<>::make() (a static member function) or from
00083  * version 2.0.4 the Cgu::Thread::make_future() helper function.  The
00084  * worker thread is then started by calling run(), and the value
00085  * extracted or waited for by calling get().  The run() method can
00086  * only be called once, but any number of threads can wait for and/or
00087  * extract the return value by calling the get() method.  The class
00088  * also provides a SafeEmitter @ref DoneEmitterAnchor "done_emitter"
00089  * public object which emits when the worker thread has finished, and
00090  * an associated when() function.
00091  *
00092  * The template parameter type of Thread::Future is the type of the
00093  * return value of the function called by the Thread::Future object.
00094  * The return value can be any type, including any arbitrarily large
00095  * tuple or other struct or standard C++ container (but see below
00096  * about copying).
00097  *
00098  * A Thread::Future object cannot represent a function with a void
00099  * return type - a compilation error will result if that is attempted.
00100  * If no return value is wanted, then the Thread::Thread class can be
00101  * used directly.  (However, if in a particular usage this class is
00102  * thought to be more convenient, the function to be represented by it
00103  * can be wrapped by another function which provides a dummy return
00104  * value, such as a dummy int.  One possible case for this is where
00105  * more than one thread wants to wait for the worker thread to
00106  * terminate, as pthread_join() and so Thread::Thread::join() only
00107  * give defined behaviour when called by one thread.)  In addition, a
00108  * Thread::Future object cannot represent a function with a non-const
00109  * reference argument - that would not normally be safe, and a compile
00110  * error will be generated if that is attempted.  However, from
00111  * version 2.0.0-rc3, const reference arguments can be bound to
00112  * Thread::Future objects (this is safe, as the Thread::Future object
00113  * will keep its own copy of the argument passed to it).
00114  * 
00115  * The make() method and make_future() functions take a plain
00116  * function, static member function or non-static member function,
00117  * which can take up to three arguments in the case of a non-static
00118  * member function, and four arguments in the case of any other
00119  * function.  Alternatively, a std::function object can be passed,
00120  * which can have any number of arguments using std::bind.
00121  *
00122  * Internal moving/copying of arguments for the target function to be
00123  * represented by the Thread::Future object takes place (once by
00124  * invoking the rvalue move constructor or lvalue copy constructor, as
00125  * appropriate, when make() or make_future() are called and, if the
00126  * argument is not a const reference argument, once when run() is
00127  * called).  Therefore, if a non-trivial class object is to be
00128  * received by the target function as an argument, it is best either
00129  * (a) if it has a rvalue constructor, to pass it to make() or
00130  * make_future() as a temporary and have the target function take a
00131  * const reference argument, or (b) for it to be constructed on free
00132  * store and for the target function to receive it by pointer or by
00133  * Cgu::SharedLockPtr.  Note also that constructing std::function
00134  * objects using std::bind can cause a number of copies of arguments
00135  * to be made, so for ordinary usage it is better to pass a function
00136  * pointer with arguments to make() or make_future() rather than a
00137  * std::function object.
00138  *
00139  * Copying of the return value of the target function represented by
00140  * the Thread::Future object also takes place.  The run() method will
00141  * store the return value of that function, so that it is available to
00142  * the get() method, and therefore copy it once (unless, that is, the
00143  * target function's return value type has an assignment operator
00144  * taking an rvalue reference argument).  The get() method will
00145  * indirectly cause it to be copied once more when the copy
00146  * constructor or assignment operator of the user's object which
00147  * receives the return value of get() is invoked.  Therefore, for
00148  * return values comprising complex class objects, it is often better
00149  * if the function represented by the Thread::Future object allocates
00150  * the return value on free store and returns it by pointer or
00151  * Cgu::SharedLockPtr.  (The example below does not do that however.)
00152  *
00153  * This is a usage example:
00154  *
00155  * @code 
00156  *   class Numbers {
00157  *   public:
00158  *     std::vector<long> get_primes(int n); // calculates the first n primes
00159  *                                          // and puts them in a vector
00160  *    ...
00161  *   };
00162  *
00163  *   Numbers obj;
00164  *
00165  *   // get the first 1,000 primes
00166  *   using namespace Cgu;
00167  *
00168  *   auto future = Thread::make_future(obj, &Numbers::get_primes, 1000);
00169  *   // Thread::make_future() is a wrapper for the equivalent long-hand version required prior to version 2.0.4:
00170  *   // auto future = Thread::Future<std::vector<long>>::make(obj, &Numbers::get_primes, 1000);
00171  *
00172  *   future->run();
00173  *   ... [ do something else ] ...
00174  *   std::vector<long> result(future->get());
00175  *   std::for_each(result.begin(), result.end(), [](long l) {std::cout << l << std::endl;});
00176  * @endcode
00177  *
00178  * If get_primes() were a static member function or plain function,
00179  * the syntax would be:
00180  *
00181  * @code 
00182  *   auto future = Thread::make_future(&Numbers::get_primes, 1000);
00183  * @endcode
00184  *
00185  * @b The @b Cgu::Thread::Future::when() @b functions
00186  *
00187  * From version 2.0.2, the return value of the thread function
00188  * represented by Cgu::Thread::Future can be obtained asynchronously
00189  * using Cgu::Thread::Future::when() to execute a function in a glib
00190  * main loop when the thread function completes.  The above example
00191  * could be reimplemented as:
00192  *
00193  * @code 
00194  *   class Numbers {
00195  *   public:
00196  *     std::vector<long> get_primes(int n); // calculates the first n primes
00197  *                                          // and puts them in a vector
00198  *    ...
00199  *   };
00200  *
00201  *   void print_primes(const std::vector<long>& result) {
00202  *     std::for_each(result.begin(), result.end(), [](long l) {std::cout << l << std::endl;});
00203  *   }
00204  *
00205  *   Numbers obj;
00206  *
00207  *   using namespace Cgu;
00208  *
00209  *   auto future = Thread::make_future(obj, &Numbers::get_primes, 1000);
00210  *   future->when(Callback::make(&print_primes));
00211  *   future->run();
00212  * @endcode
00213  *
00214  * In this example, the callback which prints the primes to the
00215  * console would execute in the default program main loop once the
00216  * thread function providing those primes returns.  As an alternative
00217  * to a free standing print_primes() function, the callback object
00218  * could be constructed from a lambda function via a std::function
00219  * object.
00220  *
00221  * @b Overloaded @b functions
00222  *
00223  * Where a member function or ordinary function represented by a
00224  * Thread::Future object is overloaded, this will cause difficulties
00225  * in template type deduction when Thread::Future<>::make() or
00226  * Thread::make_future() are called.  With Thread::Future<>::make(),
00227  * functions may be overloaded on numbers of argument without
00228  * difficulty, but not with Thread::make_future().  For example:
00229  * @code
00230  *   class Numbers {
00231  *   public:
00232  *     int calc(int i);
00233  *     int calc(int i, int j);
00234  *    ...
00235  *   };
00236  *
00237  *   Numbers obj;
00238  *
00239  *   using namespace Cgu;
00240  *
00241  *   int i = 1, j = 2;
00242  *
00243  *   auto f1 = 
00244  *     Thread::Future<int>::make(obj, &Numbers::calc, i);    // OK
00245  *   auto f2 = 
00246  *     Thread::Future<int>::make(obj, &Numbers::calc, i, j); // OK
00247  *
00248  *   // explicit is disambiguation required with Thread::future_make()
00249  *   auto f3 =
00250  *     Thread::future_make(obj, static_cast<int(Numbers::*)(int)>(&Numbers::calc), i);
00251  *   auto f4 =
00252  *     Thread::future_make(obj, static_cast<int(Numbers::*)(int, int)>(&Numbers::calc), i, j);
00253  * @endcode
00254  * Neither Thread::Future<>::make() nor Thread::make_future() can be
00255  * overloaded on types of argument without explicit disambiguation.
00256  * For example:
00257  * @code
00258  *   class Numbers {
00259  *   public:
00260  *     int calc(int i);
00261  *     int calc(double d);
00262  *    ...
00263  *   };
00264  *
00265  *   Numbers obj;
00266  *
00267  *   using namespace Cgu;
00268  *
00269  *   int i = 1;
00270  *   double d = 2.0;
00271  *
00272  *   auto f1 = 
00273  *     Thread::Future<int>::make(obj, static_cast<int (Numbers::*)(int)>(&Numbers::calc), i);
00274  *   auto f2 = 
00275  *     Thread::Future<int>::make(obj, static_cast<int (Numbers::*)(double)>(&Numbers::calc), d);
00276  *   auto f3 = 
00277  *     Thread::make_future(obj, static_cast<int (Numbers::*)(int)>(&Numbers::calc), i);
00278  *   auto f4 = 
00279  *     Thread::make_future(obj, static_cast<int (Numbers::*)(double)>(&Numbers::calc), d);
00280  * @endcode
00281  */
00282 
00283 template <class Val>
00284 class Future: public IntrusiveLockCounter {
00285 
00286   std::unique_ptr<Cgu::Thread::Thread> thread_u;
00287   std::unique_ptr<Cgu::Callback::Callback> cb_u;
00288 
00289   mutable Mutex mutex;
00290   Cond cond;
00291   Val val;
00292   bool done;
00293   bool running;
00294   bool error;
00295   bool emitter_error;
00296 
00297   template <class T, class Ret, class... Args>
00298   void run_wrapper(T*, Ret (T::*)(Args...), const Args&...);
00299 
00300   template <class T, class Ret, class... Args>
00301   void run_wrapper_const(const T*, Ret (T::*)(Args...) const, const Args&...);
00302 
00303   template <class Ret, class... Args>
00304   void run_wrapper_static(Ret (*)(Args...), const Args&...);
00305 
00306   void run_wrapper_func(const std::function<Val(void)>&);
00307 
00308   void cancel_cleanup();
00309 
00310   void execute_done(const Cgu::Callback::SafeFunctorArg<const Val&>&);
00311   void post_done(const Cgu::Callback::SafeFunctorArg<const Val&>&,
00312                  gint, GMainContext*);
00313   void execute_done_rel(const Cgu::SharedLockPtr<Cgu::SafeEmitterArg<const Val&>>&);
00314   void post_done_rel(const Cgu::SharedLockPtr<Cgu::SafeEmitterArg<const Val&>>&,
00315                      gint, GMainContext*);
00316 
00317   // this is a static function taking the future object by IntrusivePtr to
00318   // ensure that the future object remains in existence whilst this
00319   // function might execute
00320   static void fail_cb(const Cgu::IntrusivePtr<Future<Val>>& future,
00321                       const Cgu::Callback::SafeFunctor& func,
00322                       bool& ret);
00323 
00324   // private constructor - this class can only be created with Thread::Future::make()
00325   Future(): val(), done(false), running(false), error(false), emitter_error(false) {}
00326 
00327 public:
00328 
00329   // this class cannot be copied except by smart pointer
00330 /**
00331  * This class cannot be copied (except by smart pointer).  The copy
00332  * constructor is deleted.
00333  */
00334   Future(const Future&) = delete;
00335 
00336 /**
00337  * This class cannot be copied (except by smart pointer).  The
00338  * assignment operator is deleted.
00339  */
00340   Future& operator=(const Future&) = delete;
00341 
00342 /**
00343  * Constructs a new Cgu::Thread::Future object (returned by
00344  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00345  * Val represents the return value of the function to be represented
00346  * by the new object.  From version 2.0.4, it will usually be more
00347  * convenient to call the Cgu::Thread::make_future() function, which
00348  * is a convenience wrapper for this static method.
00349  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00350  * is exhausted and the system throws in that case.  (This exception
00351  * will not be thrown if the library has been installed using the
00352  * --with-glib-memory-slices-no-compat configuration option: instead
00353  * glib will terminate the program if it is unable to obtain memory
00354  * from the operating system.)  It will also throw if the default
00355  * constructor of the return value type throws.
00356  */
00357   template <class Ret, class T>
00358   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(T& t,
00359                                                           Ret (T::*func)());
00360 
00361 /**
00362  * Constructs a new Cgu::Thread::Future object (returned by
00363  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00364  * Val represents the return value of the function to be represented
00365  * by the new object.  From version 2.0.4, it will usually be more
00366  * convenient to call the Cgu::Thread::make_future() function, which
00367  * is a convenience wrapper for this static method.
00368  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00369  * is exhausted and the system throws in that case.  (This exception
00370  * will not be thrown if the library has been installed using the
00371  * --with-glib-memory-slices-no-compat configuration option: instead
00372  * glib will terminate the program if it is unable to obtain memory
00373  * from the operating system.)  It will also throw if the copy
00374  * constructor or assignment operator of the bound argument throws, or
00375  * the default constructor of the return value type throws.
00376  */
00377   template <class Ret, class Param1, class Arg1, class T>
00378   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(T& t,
00379                                                           Ret (T::*func)(Param1),
00380                                                           Arg1&& arg1);
00381 
00382 /**
00383  * Constructs a new Cgu::Thread::Future object (returned by
00384  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00385  * Val represents the return value of the function to be represented
00386  * by the new object.  From version 2.0.4, it will usually be more
00387  * convenient to call the Cgu::Thread::make_future() function, which
00388  * is a convenience wrapper for this static method.
00389  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00390  * is exhausted and the system throws in that case.  (This exception
00391  * will not be thrown if the library has been installed using the
00392  * --with-glib-memory-slices-no-compat configuration option: instead
00393  * glib will terminate the program if it is unable to obtain memory
00394  * from the operating system.)  It will also throw if the copy
00395  * constructor or assignment operator of a bound argument throws, or
00396  * the default constructor of the return value type throws.
00397  */
00398   template <class Ret, class Param1, class Param2, class Arg1, class Arg2, class T>
00399   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(T& t,
00400                                                           Ret (T::*func)(Param1, Param2),
00401                                                           Arg1&& arg1,
00402                                                           Arg2&& arg2);
00403 
00404 /**
00405  * Constructs a new Cgu::Thread::Future object (returned by
00406  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00407  * Val represents the return value of the function to be represented
00408  * by the new object.  From version 2.0.4, it will usually be more
00409  * convenient to call the Cgu::Thread::make_future() function, which
00410  * is a convenience wrapper for this static method.
00411  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00412  * is exhausted and the system throws in that case.  (This exception
00413  * will not be thrown if the library has been installed using the
00414  * --with-glib-memory-slices-no-compat configuration option: instead
00415  * glib will terminate the program if it is unable to obtain memory
00416  * from the operating system.)  It will also throw if the copy
00417  * constructor or assignment operator of a bound argument throws, or
00418  * the default constructor of the return value type throws.
00419  */
00420   template <class Ret, class Param1, class Param2, class Param3,
00421             class Arg1, class Arg2, class Arg3, class T>
00422   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(T& t,
00423                                                           Ret (T::*func)(Param1, Param2, Param3),
00424                                                           Arg1&& arg1,
00425                                                           Arg2&& arg2,
00426                                                           Arg3&& arg3);
00427 
00428 /**
00429  * Constructs a new Cgu::Thread::Future object (returned by
00430  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00431  * Val represents the return value of the function to be represented
00432  * by the new object.  From version 2.0.4, it will usually be more
00433  * convenient to call the Cgu::Thread::make_future() function, which
00434  * is a convenience wrapper for this static method.
00435  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00436  * is exhausted and the system throws in that case.  (This exception
00437  * will not be thrown if the library has been installed using the
00438  * --with-glib-memory-slices-no-compat configuration option: instead
00439  * glib will terminate the program if it is unable to obtain memory
00440  * from the operating system.)  It will also throw if the default
00441  * constructor of the return value type throws.
00442  */
00443   template <class Ret, class T>
00444   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(const T& t,
00445                                                           Ret (T::*func)() const);
00446 
00447 /**
00448  * Constructs a new Cgu::Thread::Future object (returned by
00449  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00450  * Val represents the return value of the function to be represented
00451  * by the new object.  From version 2.0.4, it will usually be more
00452  * convenient to call the Cgu::Thread::make_future() function, which
00453  * is a convenience wrapper for this static method.
00454  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00455  * is exhausted and the system throws in that case.  (This exception
00456  * will not be thrown if the library has been installed using the
00457  * --with-glib-memory-slices-no-compat configuration option: instead
00458  * glib will terminate the program if it is unable to obtain memory
00459  * from the operating system.)  It will also throw if the copy
00460  * constructor or assignment operator of the bound argument throws, or
00461  * the default constructor of the return value type throws.
00462  */
00463   template <class Ret, class Param1, class Arg1, class T>
00464   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(const T& t,
00465                                                           Ret (T::*func)(Param1) const,
00466                                                           Arg1&& arg1);
00467 
00468 /**
00469  * Constructs a new Cgu::Thread::Future object (returned by
00470  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00471  * Val represents the return value of the function to be represented
00472  * by the new object.  From version 2.0.4, it will usually be more
00473  * convenient to call the Cgu::Thread::make_future() function, which
00474  * is a convenience wrapper for this static method.
00475  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00476  * is exhausted and the system throws in that case.  (This exception
00477  * will not be thrown if the library has been installed using the
00478  * --with-glib-memory-slices-no-compat configuration option: instead
00479  * glib will terminate the program if it is unable to obtain memory
00480  * from the operating system.)  It will also throw if the copy
00481  * constructor or assignment operator of a bound argument throws, or
00482  * the default constructor of the return value type throws.
00483  */
00484   template <class Ret, class Param1, class Param2, class Arg1, class Arg2, class T>
00485   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(const T& t,
00486                                                           Ret (T::*func)(Param1, Param2) const,
00487                                                           Arg1&& arg1,
00488                                                           Arg2&& arg2);
00489 
00490 /**
00491  * Constructs a new Cgu::Thread::Future object (returned by
00492  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00493  * Val represents the return value of the function to be represented
00494  * by the new object.  From version 2.0.4, it will usually be more
00495  * convenient to call the Cgu::Thread::make_future() function, which
00496  * is a convenience wrapper for this static method.
00497  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00498  * is exhausted and the system throws in that case.  (This exception
00499  * will not be thrown if the library has been installed using the
00500  * --with-glib-memory-slices-no-compat configuration option: instead
00501  * glib will terminate the program if it is unable to obtain memory
00502  * from the operating system.)  It will also throw if the copy
00503  * constructor or assignment operator of a bound argument throws, or
00504  * the default constructor of the return value type throws.
00505  */
00506   template <class Ret, class Param1, class Param2, class Param3,
00507             class Arg1, class Arg2, class Arg3, class T>
00508   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(const T& t,
00509                                                           Ret (T::*func)(Param1, Param2, Param3) const,
00510                                                           Arg1&& arg1,
00511                                                           Arg2&& arg2,
00512                                                           Arg3&& arg3);
00513 
00514 /**
00515  * Constructs a new Cgu::Thread::Future object (returned by
00516  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00517  * Val represents the return value of the function to be represented
00518  * by the new object.  From version 2.0.4, it will usually be more
00519  * convenient to call the Cgu::Thread::make_future() function, which
00520  * is a convenience wrapper for this static method.
00521  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00522  * is exhausted and the system throws in that case.  (This exception
00523  * will not be thrown if the library has been installed using the
00524  * --with-glib-memory-slices-no-compat configuration option: instead
00525  * glib will terminate the program if it is unable to obtain memory
00526  * from the operating system.)  It will also throw if the default
00527  * constructor of the return value type throws.
00528  */
00529   template <class Ret>
00530   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)());
00531 
00532 /**
00533  * Constructs a new Cgu::Thread::Future object (returned by
00534  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00535  * Val represents the return value of the function to be represented
00536  * by the new object.  From version 2.0.4, it will usually be more
00537  * convenient to call the Cgu::Thread::make_future() function, which
00538  * is a convenience wrapper for this static method.
00539  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00540  * is exhausted and the system throws in that case.  (This exception
00541  * will not be thrown if the library has been installed using the
00542  * --with-glib-memory-slices-no-compat configuration option: instead
00543  * glib will terminate the program if it is unable to obtain memory
00544  * from the operating system.)  It will also throw if the copy
00545  * constructor or assignment operator of the bound argument throws, or
00546  * the default constructor of the return value type throws.
00547  */
00548   template <class Ret, class Param1, class Arg1>
00549   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)(Param1),
00550                                                           Arg1&& arg1);
00551 
00552 /**
00553  * Constructs a new Cgu::Thread::Future object (returned by
00554  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00555  * Val represents the return value of the function to be represented
00556  * by the new object.  From version 2.0.4, it will usually be more
00557  * convenient to call the Cgu::Thread::make_future() function, which
00558  * is a convenience wrapper for this static method.
00559  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00560  * is exhausted and the system throws in that case.  (This exception
00561  * will not be thrown if the library has been installed using the
00562  * --with-glib-memory-slices-no-compat configuration option: instead
00563  * glib will terminate the program if it is unable to obtain memory
00564  * from the operating system.)  It will also throw if the copy
00565  * constructor or assignment operator of a bound argument throws, or
00566  * the default constructor of the return value type throws.
00567  */
00568   template <class Ret, class Param1, class Param2, class Arg1, class Arg2>
00569   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)(Param1, Param2),
00570                                                           Arg1&& arg1,
00571                                                           Arg2&& arg2);
00572 
00573 /**
00574  * Constructs a new Cgu::Thread::Future object (returned by
00575  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00576  * Val represents the return value of the function to be represented
00577  * by the new object.  From version 2.0.4, it will usually be more
00578  * convenient to call the Cgu::Thread::make_future() function, which
00579  * is a convenience wrapper for this static method.
00580  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00581  * is exhausted and the system throws in that case.  (This exception
00582  * will not be thrown if the library has been installed using the
00583  * --with-glib-memory-slices-no-compat configuration option: instead
00584  * glib will terminate the program if it is unable to obtain memory
00585  * from the operating system.)  It will also throw if the copy
00586  * constructor or assignment operator of a bound argument throws, or
00587  * the default constructor of the return value type throws.
00588  */
00589   template <class Ret, class Param1, class Param2, class Param3,
00590             class Arg1, class Arg2, class Arg3>
00591   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)(Param1, Param2, Param3),
00592                                                           Arg1&& arg1,
00593                                                           Arg2&& arg2,
00594                                                           Arg3&& arg3);
00595 
00596 /**
00597  * Constructs a new Cgu::Thread::Future object (returned by
00598  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00599  * Val represents the return value of the function to be represented
00600  * by the new object.  From version 2.0.4, it will usually be more
00601  * convenient to call the Cgu::Thread::make_future() function, which
00602  * is a convenience wrapper for this static method.
00603  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00604  * is exhausted and the system throws in that case.  (This exception
00605  * will not be thrown if the library has been installed using the
00606  * --with-glib-memory-slices-no-compat configuration option: instead
00607  * glib will terminate the program if it is unable to obtain memory
00608  * from the operating system.)  It will also throw if the copy
00609  * constructor or assignment operator of a bound argument throws, or
00610  * the default constructor of the return value type throws.
00611  */
00612   template <class Ret, class Param1, class Param2, class Param3, class Param4,
00613             class Arg1, class Arg2, class Arg3, class Arg4>
00614   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(Ret (*func)(Param1, Param2, Param3, Param4),
00615                                                           Arg1&& arg1,
00616                                                           Arg2&& arg2,
00617                                                           Arg3&& arg3,
00618                                                           Arg4&& arg4);
00619 
00620 /**
00621  * Constructs a new Cgu::Thread::Future object (returned by
00622  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00623  * Val represents the return value of the function to be represented
00624  * by the new object.  From version 2.0.4, it will usually be more
00625  * convenient to call the Cgu::Thread::make_future() function, which
00626  * is a convenience wrapper for this static method.
00627  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00628  * is exhausted and the system throws in that case.  (This exception
00629  * will not be thrown if the library has been installed using the
00630  * --with-glib-memory-slices-no-compat configuration option: instead
00631  * glib will terminate the program if it is unable to obtain memory
00632  * from the operating system.)  It will also throw if the copy
00633  * constructor or assignment operator of a bound argument throws, or
00634  * the default constructor of the return value type throws.
00635  */
00636   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(const std::function<Val(void)>& func);
00637 
00638 /**
00639  * Constructs a new Cgu::Thread::Future object (returned by
00640  * Cgu::IntrusivePtr<Cgu::Thread::Future<Val>>).  The type parameter
00641  * Val represents the return value of the function to be represented
00642  * by the new object.  From version 2.0.4, it will usually be more
00643  * convenient to call the Cgu::Thread::make_future() function, which
00644  * is a convenience wrapper for this static method.
00645  * @exception std::bad_alloc It might throw std::bad_alloc if memory
00646  * is exhausted and the system throws in that case.  (This exception
00647  * will not be thrown if the library has been installed using the
00648  * --with-glib-memory-slices-no-compat configuration option: instead
00649  * glib will terminate the program if it is unable to obtain memory
00650  * from the operating system.)  It will also throw if the copy
00651  * constructor or assignment operator of a bound argument throws, or
00652  * the default constructor of the return value type throws.
00653  */
00654   static Cgu::IntrusivePtr<Cgu::Thread::Future<Val>> make(std::function<Val(void)>&& func);
00655 
00656 /**
00657  * Runs the function represented by this Cgu::Thread::Future object in
00658  * a new worker thread.  That function will only be run once.  If this
00659  * is the first time this method has been called, it will start the
00660  * worker thread and return true, and if it has previously been
00661  * called, this method will do nothing and return false.  This method
00662  * is thread safe and may be called by a different thread from the one
00663  * which called make().
00664  * @return true if this is the first time this method has been called,
00665  * or false if this method has previously been called.
00666  * @exception Cgu::Thread::FutureThreadError This method might throw
00667  * Cgu::Thread::FutureThreadError if it has not previously been called
00668  * and the thread did not start properly.  If it does throw, this
00669  * Cgu::Thread::Future object is defunct and further attempts to call
00670  * this method will return immediately with a false value.  (It is
00671  * often not worth checking for this exception, as it means either
00672  * memory is exhausted, the pthread thread limit has been reached or
00673  * pthread has run out of other resources to start new threads.)
00674  * @exception std::bad_alloc This method might throw std::bad_alloc if
00675  * it has not previously been called, and memory is exhausted and the
00676  * system throws in that case.  If it does throw, this
00677  * Cgu::Thread::Future object is defunct and further attempts to call
00678  * this method will return immediately with a false value.  (This
00679  * exception will not be thrown if the library has been installed
00680  * using the --with-glib-memory-slices-no-compat configuration option:
00681  * instead glib will terminate the program if it is unable to obtain
00682  * memory from the operating system.)
00683  * @note 1. Any Cgu::Thread::Exit exception, or any uncaught exception
00684  * derived from std::exception, which is thrown from the worker thread
00685  * will be caught and consumed and the error flag will be set.  The
00686  * worker thread will safely terminate and unwind the stack in so
00687  * doing.
00688  * @note 2. As this wrapper class can provide error reporting in a way
00689  * that Cgu::Thread::Thread of itself cannot, it would be desirable to
00690  * consume any other uncaught exceptions.  However, this cannot be
00691  * done: annoyingly, NPTL's forced stack unwinding does not allow this
00692  * if thread cancellation is to be made available.  If an uncaught
00693  * exception propagates out of a thread when the thread exits, the
00694  * C++11 standard will cause std::terminate() to be called and so
00695  * terminate the entire program.  Accordingly, a user must make sure
00696  * that no exceptions, other than Cgu::Thread::Exit or those derived
00697  * from std::exception or any cancellation pseudo-exception, can
00698  * propagate from the function which this Cgu::Thread::Future object
00699  * represents.
00700  * @note 3. If the worker thread is cancelled by a call to cancel()
00701  * while in the middle of executing the function which this
00702  * Cgu::Thread::Future object represents, the error flag will be set.
00703  */
00704   bool run();
00705 
00706 /**
00707  * Gets the value obtained from the function which is represented by
00708  * this object.  If the worker thread launched by the call to run()
00709  * has not completed, then this method will block until it has
00710  * completed.  If run() has not been called, then run() will be called
00711  * (and this method will block until the launched worker thread
00712  * completes).  If the function which is represented by this object
00713  * throws Cgu::Thread::Exit or an uncaught exception derived from
00714  * std::exception, then the exception will have been consumed by this
00715  * Cgu::Thread::Future object and the error flag will have been set.
00716  * The error flag will also have been set if the worker thread is
00717  * cancelled or the thread wrapper in this Cgu::Thread::Future object
00718  * threw std::bad_alloc.  This method is thread safe and may be called
00719  * by any thread (and by more than one thread).  It is also strongly
00720  * exception safe: no data will be lost if extracting the value fails.
00721  * @return The value obtained from the function which is represented
00722  * by this object
00723  * @exception Cgu::Thread::FutureThreadError This method might throw
00724  * Cgu::Thread::FutureThreadError if run() has not previously been
00725  * called and the thread did not start properly when this function
00726  * called run().
00727  * @exception std::bad_alloc This method might throw std::bad_alloc if
00728  * run() has not previously been called, memory is exhausted and the
00729  * system throws in that case.  (This exception will not be thrown if
00730  * the library has been installed using the
00731  * --with-glib-memory-slices-no-compat configuration option: instead
00732  * glib will terminate the program if it is unable to obtain memory
00733  * from the operating system.)
00734  * @note This method might also throw if the copy constructor or
00735  * assignment operator of the returned value type throws.
00736  */
00737   Val get();
00738 
00739 /**
00740  * Cancels the worker thread in which the function represented by this
00741  * object runs, if that function has not yet finished.  If this method
00742  * is called and the worker thread is still running and is cancelled
00743  * in response to a call to this method, then the error flag will be
00744  * set so that a method calling get() can examine whether the result
00745  * is valid.  If run() has not yet been called or the worker thread
00746  * has already finished executing the function represented by this
00747  * object then this function does nothing and returns false.  This
00748  * method is thread safe and may be called by any thread.  It will not
00749  * throw.
00750  * @return true if run() has previously been called and the worker
00751  * thread has not yet finished executing the function represented by
00752  * this object, otherwise false (in which case this method does
00753  * nothing).
00754  * @note 1. Use this method with care.  When cancelling a thread not
00755  * all thread implementations will unwind the stack, and so run the
00756  * destructors of local objects.  This is discussed further in the
00757  * documentation on Cgu::Thread::Thread::cancel().
00758  * @note 2. This method might return true because the worker thread
00759  * has not yet finished, but the error flag might still not be set.
00760  * This is because the worker thread may not meet a cancellation point
00761  * before it ends naturally.  It is the error flag which indicates
00762  * definitively whether the worker thread terminated prematurely in
00763  * response to a call to this method.
00764  */
00765   bool cancel();
00766 
00767 /**
00768  * A utility enabling the value returned by the thread function
00769  * represented by this Cgu::Thread::Future object to be dealt with
00770  * asynchronously rather than by (or in addition to) a call to the
00771  * get() method.  It causes the callback passed as an argument to this
00772  * method (referred to below as the 'when' callback) to be executed by
00773  * a thread's main loop if and when the thread function represented by
00774  * this Cgu::Thread::Future object finishes correctly - the 'when'
00775  * callback is passed that thread function's return value when it is
00776  * invoked.  This method is thread safe, and may be called by any
00777  * thread.
00778  *
00779  * This functionality is implemented by connecting an internal
00780  * dispatching callback to the done_emitter object.
00781  *
00782  * The 'when' callback should take a single unbound argument
00783  * comprising a const reference to the return type of the thread
00784  * function represented by this Cgu::Thread::Future object.  (So, in
00785  * the case of a Future<int> object, the callback function should take
00786  * a const int& argument as the unbound argument.)  The 'when'
00787  * callback can have any number of bound arguments, except that a
00788  * bound argument may not include a copy of this Cgu::Thread::Future
00789  * object held by intrusive pointer as returned by the make() methods
00790  * (that would result in this Cgu::Thread::Future object owning, via
00791  * done_emitter, a reference to itself and so become incapable of
00792  * being freed).  The 'when' callback may, however, take a pointer to
00793  * this Cgu::Thread::Future object, as obtained by the
00794  * Cgu::IntrusivePtr::get() method, because this Cgu::Thread::Future
00795  * object is guaranteed to remain in existence until the callback has
00796  * completed executing.
00797  *
00798  * This method cannot be called after the thread function represented
00799  * by this Cgu::Thread::Future object has completed (either
00800  * successfully or unsuccessfully) so that is_done() would return
00801  * true, and if this is attempted a Cgu::Thread::FutureWhenError
00802  * exception will be thrown.  Therefore, generally this method should
00803  * be called before the run() method has been called.
00804  *
00805  * Once the run() method has been called, this Cgu::Thread::Future
00806  * object will always stay in existence until the thread function
00807  * represented by it has completed (whether correctly, by cancellation
00808  * or by a thrown exception), and any 'when' callback (and any other
00809  * callbacks connected to the done_emitter object) and any 'fail'
00810  * callback have completed.  Accordingly it is safe to use this method
00811  * even if the intrusive pointer object returned by the make() methods
00812  * will go out of scope before the 'when' callback has executed: the
00813  * callback will execute correctly irrespective of that.
00814  *
00815  * Summary: use of this method is safe and has been implemented in a
00816  * way which does not give rise to timing issues.
00817  *
00818  * If memory is exhausted and std::bad_alloc is thrown by the thread
00819  * wrapper of Cgu::Thread::Future after run() is called or by
00820  * done_emitter when emitting, or if the thread function represented
00821  * by this Cgu::Thread::Future object throws Cgu::Thread::Exit, exits
00822  * with an uncaught exception deriving from std::exception or is
00823  * cancelled, or if the copy constructor of a non-reference bound
00824  * argument of the 'when' callback throws, or any other callback has
00825  * been connected to done_emitter before this method is called which
00826  * exits with an uncaught exception, then the 'when' callback will not
00827  * execute (instead the exception concerned will be consumed and an
00828  * error indicated).  With many systems, swap memory combined with
00829  * memory over-commit makes it pointless to check for std::bad_alloc
00830  * (and even more so in programs using glib, as glib aborts a program
00831  * where it cannot obtain memory from the operating system).  So
00832  * subject to that, if the user program is designed so that the thread
00833  * function represented by this Cgu::Thread::Future object does not
00834  * exit with uncaught exceptions, does not throw Cgu::Thread::Exit and
00835  * is not cancelled, and so that the 'when' callback does not exit
00836  * with an uncaught exception and either has no non-reference bound
00837  * arguments or the copy constructors of any non-reference bound
00838  * arguments do not throw, and if this method is called before any
00839  * other callbacks are connected to done_emitter, the possibility of
00840  * failure can be disregarded.
00841  *
00842  * In cases where that is not true and detecting whether a failure has
00843  * occurred is required, a fail() method is provided.  It should be
00844  * noted that a callback handed to the fail() method will not execute
00845  * in a case of error if the error comprises the 'when' callback
00846  * exiting with an uncaught exception when it is executed by the main
00847  * loop, or the copy constructor of one of its non-reference bound
00848  * arguments throwing when it executes (such an exception would be
00849  * consumed internally in order to protect the main loop and a
00850  * g_critical message issued).  If the 'when' callback might exit with
00851  * an uncaught exception when executing or have the copy constructor
00852  * of a non-reference bound argument throw, and doing something other
00853  * than consuming the exception and issuing a g_critical message is
00854  * required, then a different approach is to start a new thread to
00855  * wait on the get() method which can act on the result of is_error()
00856  * directly.
00857  *
00858  * The glib main loop must have been made thread-safe by a call to
00859  * g_thread_init() before this function is called.
00860  *
00861  * @param cb The 'when' callback (the callback to be executed when the
00862  * function represented by this Cgu::Thread::Future object has
00863  * successfully completed).  Ownership is taken of this object, and it
00864  * will be deleted when it has been finished with.
00865  * @param priority The priority to be given to the 'when' callback in
00866  * the main loop after the thread function represented by this
00867  * Cgu::Thread::Future object has successfully completed.  In
00868  * ascending order of priorities, priorities are G_PRIORITY_LOW,
00869  * G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT
00870  * and G_PRIORITY_HIGH. The default is G_PRIORITY_DEFAULT.  This
00871  * determines the order in which the callback will appear in the event
00872  * list in the main loop, not the priority which the OS will adopt.
00873  * @param context The glib main context of the thread in whose main
00874  * loop the 'when' callback is to be executed (the default of NULL
00875  * will cause the callback to be executed in the main program loop).
00876  * @return The internal dispatching callback created by this method
00877  * and connected to done_emitter.  It is made available as a return
00878  * value so that if wanted it can be disconnected programmatically
00879  * from done_emitter, or block()/unblock() can be called on it (but if
00880  * that is to be done, it must be done before the thread function
00881  * represented by this Cgu::Thread::Future object has completed in
00882  * order for it to be effective).
00883  * @exception Cgu::Thread::FutureWhenError This method will throw
00884  * Cgu::Thread::FutureWhenError if it is called after the thread
00885  * function represented by this Cgu::Thread::Future object has
00886  * completed.  If it does so, the 'when' callback will be disposed of.
00887  * @exception std::bad_alloc This method might throw std::bad_alloc if
00888  * memory is exhausted and the system throws in that case.  If it does
00889  * so, the 'when' callback will be disposed of.
00890  * @note The return value of the function represented by the
00891  * Cgu::Thread::Future object is passed as an argument to the callback
00892  * by const reference.  This should be taken into account if the
00893  * return value is of class type and other threads might access it
00894  * concurrently via the get() method by const reference (that is,
00895  * without copying it), where any of that return value's const methods
00896  * are not thread safe.
00897  *
00898  * Since 2.0.2
00899  */
00900   Cgu::Callback::SafeFunctor when(const Cgu::Callback::CallbackArg<const Val&>* cb,
00901                                   gint priority = G_PRIORITY_DEFAULT,
00902                                   GMainContext* context = 0);
00903 
00904 /**
00905  * This is a version of the utility enabling the value returned by the
00906  * thread function represented by this Cgu::Thread::Future object to
00907  * be dealt with asynchronously, which takes a Releaser object for
00908  * automatic disconnection of the callback passed as an argument to
00909  * this method (referred to below as the 'when' callback), if the
00910  * object having the 'when' callback function as a member is
00911  * destroyed.  For this to be race free, the lifetime of that object
00912  * must be controlled by the thread in whose main loop the 'when'
00913  * callback will execute.
00914  *
00915  * If the 'when' callback has not been released, this method causes it
00916  * to be executed by a thread's main loop if and when the thread
00917  * function represented by this Cgu::Thread::Future object finishes
00918  * correctly - the 'when' callback is passed that thread function's
00919  * return value when it is invoked.  This method is thread safe, and
00920  * may be called by any thread.
00921  *
00922  * This functionality is implemented by connecting an internal
00923  * dispatching callback to the done_emitter object.
00924  *
00925  * The 'when' callback should take a single unbound argument
00926  * comprising a const reference to the return type of the thread
00927  * function represented by this Cgu::Thread::Future object.  (So, in
00928  * the case of a Future<int> object, the callback function should take
00929  * a const int& argument as the unbound argument.)  The 'when'
00930  * callback can have any number of bound arguments, except that a
00931  * bound argument may not include a copy of this Cgu::Thread::Future
00932  * object held by intrusive pointer as returned by the make() methods
00933  * (that would result in this Cgu::Thread::Future object owning, via
00934  * done_emitter, a reference to itself and so become incapable of
00935  * being freed).  The 'when' callback may, however, take a pointer to
00936  * this Cgu::Thread::Future object, as obtained by the
00937  * Cgu::IntrusivePtr::get() method, because this Cgu::Thread::Future
00938  * object is guaranteed to remain in existence until the callback has
00939  * completed executing.
00940  *
00941  * This method cannot be called after the thread function represented
00942  * by this Cgu::Thread::Future object has completed (either
00943  * successfully or unsuccessfully) so that is_done() would return
00944  * true, and if this is attempted a Cgu::Thread::FutureWhenError
00945  * exception will be thrown.  Therefore, generally this method should
00946  * be called before the run() method has been called.
00947  *
00948  * The documentation for the version of this method which does not
00949  * take a Releaser object gives further details of how this method is
00950  * used.
00951  *
00952  * The glib main loop must have been made thread-safe by a call to
00953  * g_thread_init() before this function is called.
00954  *
00955  * @param cb The 'when' callback (the callback to be executed when the
00956  * function represented by this Cgu::Thread::Future object has
00957  * successfully completed).  Ownership is taken of this object, and it
00958  * will be deleted when it has been finished with.
00959  * @param r A Releaser object for automatic disconnection of the
00960  * 'when' callback if the object of which the callback function is a
00961  * member is destroyed.
00962  * @param priority The priority to be given to the 'when' callback in
00963  * the main loop after the thread function represented by this
00964  * Cgu::Thread::Future object has successfully completed.  In
00965  * ascending order of priorities, priorities are G_PRIORITY_LOW,
00966  * G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT
00967  * and G_PRIORITY_HIGH. The default is G_PRIORITY_DEFAULT.  This
00968  * determines the order in which the callback will appear in the event
00969  * list in the main loop, not the priority which the OS will adopt.
00970  * @param context The glib main context of the thread in whose main
00971  * loop the 'when' callback is to be executed (the default of NULL
00972  * will cause the callback to be executed in the main program loop).
00973  * @return The internal dispatching callback created by this method
00974  * and connected to done_emitter.  It is made available as a return
00975  * value so that if wanted it can be disconnected programmatically
00976  * from done_emitter, or block()/unblock() can be called on it (but if
00977  * that is to be done, it must be done before the thread function
00978  * represented by this Cgu::Thread::Future object has completed in
00979  * order for it to be effective).
00980  * @exception Cgu::Thread::FutureWhenError This method will throw
00981  * Cgu::Thread::FutureWhenError if it is called after the thread
00982  * function represented by this Cgu::Thread::Future object has
00983  * completed.  If it does so, the 'when' callback will be disposed of.
00984  * @exception std::bad_alloc This method might throw std::bad_alloc if
00985  * memory is exhausted and the system throws in that case.  If it does
00986  * so, the 'when' callback will be disposed of.
00987  * @exception Cgu::Thread::MutexError This method will throw
00988  * Cgu:Thread::MutexError if initialisation of the mutex in a
00989  * SafeEmitterArg object constructed by this method fails.  If it does
00990  * so, the 'when' callback will be disposed of.  (It is often not
00991  * worth checking for this, as it means either memory is exhausted or
00992  * pthread has run out of other resources to create new mutexes.)
00993  * @note The return value of the function represented by the
00994  * Cgu::Thread::Future object is passed as an argument to the callback
00995  * by const reference.  This should be taken into account if the
00996  * return value is of class type and other threads might access it
00997  * concurrently via the get() method by const reference (that is,
00998  * without copying it), where any of that return value's const methods
00999  * are not thread safe.
01000  *
01001  * Since 2.0.2
01002  */
01003   Cgu::Callback::SafeFunctor when(const Cgu::Callback::CallbackArg<const Val&>* cb,
01004                                   Cgu::Releaser& r,
01005                                   gint priority = G_PRIORITY_DEFAULT,
01006                                   GMainContext* context = 0);
01007 
01008 /**
01009  * A utility intended to be used where relevant in conjunction with
01010  * the when() methods.  It enables a callback to be executed in a glib
01011  * main loop (referred to below as the 'fail' callback) if memory is
01012  * exhausted and std::bad_alloc was thrown by the thread wrapper of
01013  * Cgu::Thread::Future after calling run() or by done_emitter when
01014  * emitting, or if the thread function represented by this
01015  * Cgu::Thread::Future object threw Cgu::Thread::Exit, exited with an
01016  * uncaught exception deriving from std::exception or was cancelled,
01017  * or any callback connected to done_emitter exited with an uncaught
01018  * exception.  It therefore enables errors to be detected and acted on
01019  * without having a thread wait on the get() method in order to test
01020  * is_error() or is_emitter_error().
01021  *
01022  * It is implemented by attaching a timeout to the main loop which
01023  * polls at 100 millisecond intervals and tests is_done()/is_error()
01024  * and is_emitter_done()/is_emitter_error().  The timeout is
01025  * automatically removed by the implementation once it has been
01026  * detected that an error has occurred and the 'fail' callback is
01027  * executed, or if the thread function represented by this Cgu::Future
01028  * object and all done_emitter emissions (including execution of any
01029  * 'when' callback) have completed successfully.
01030  *
01031  * This method can be called before or after the run() method has been
01032  * called, and whether or not the thread function represented by this
01033  * Cgu::Thread::Future object has completed.
01034  *
01035  * Once this method has been called, this Cgu::Thread::Future object
01036  * will always stay in existence until the timeout has been
01037  * automatically removed by the implementation.  Accordingly it is
01038  * safe to use this method even if the intrusive pointer object
01039  * returned by the make() methods will go out of scope before the
01040  * 'fail' callback has executed: the callback will execute correctly
01041  * irrespective of that.
01042  *
01043  * This method does not have a priority argument: as a polling timeout
01044  * is created, a particular priority will normally have no
01045  * significance (in fact, the 'fail' callback will execute in the main
01046  * loop with a priority of G_PRIORITY_DEFAULT).  If in a special case
01047  * a different polling interval than 100 milliseconds or a different
01048  * priority is required, users can attach their own polling timeouts
01049  * to a main loop and carry out the tests by hand.
01050  *
01051  * Four other points should be noted.  First, if as well as the when()
01052  * method being called some other callback has been connected to
01053  * done_emitter, and that other callback throws, the 'fail' callback
01054  * will execute.  Therefore, if the particular program design requires
01055  * that the 'fail' callback should only execute if the thread function
01056  * represented by this Cgu::Thread::Future object did not complete
01057  * successfully or emitting the 'when' callback failed, no other
01058  * callbacks which throw should be connected to done_emitter.
01059  *
01060  * Secondly, as mentioned in the documentation on the when() method,
01061  * if the 'when' callback exits with an uncaught exception upon being
01062  * executed by the main loop or has a non-reference bound argument
01063  * whose copy constructor throws when it executes, the 'fail' callback
01064  * will not execute (the exception will have been consumed internally
01065  * in order to protect the main loop and a g_critical message issued).
01066  *
01067  * Thirdly, avoid if possible having the 'fail' callback represent a
01068  * function which might throw or which has a non-reference bound
01069  * argument whose copy constructor might throw (such an exception
01070  * would be consumed internally in order to protect the main loop and
01071  * a g_critical message issued, but no other error indication apart
01072  * from the g_critical message will be provided).
01073  *
01074  * Fourthly, unlike the 'when' callback, a copy of this
01075  * Cgu::Thread::Future object held by intrusive pointer as returned by
01076  * the make() methods may safely be bound to the 'fail' callback,
01077  * which would enable the 'fail' callback to determine whether it is
01078  * is_error() or is_emitter_error() which returns false.
01079  *
01080  * The glib main loop must have been made thread-safe by a call to
01081  * g_thread_init() before this function is called.
01082  *
01083  * @param cb The 'fail' callback (the callback to be executed if the
01084  * thread function represented by this Cgu::Thread::Future object or a
01085  * done_emitter emission has failed to complete).  Ownership is taken
01086  * of this object, and it will be deleted when it has been finished
01087  * with.
01088  * @param context The glib main context of the thread in whose main
01089  * loop the 'fail' callback is to be executed (the default of NULL
01090  * will cause the functor to be executed in the main program loop).
01091  * @exception std::bad_alloc This method might throw std::bad_alloc if
01092  * memory is exhausted and the system throws in that case.  If it does
01093  * so, the 'fail' callback will be disposed of.
01094  *
01095  * Since 2.0.2
01096  */
01097   void fail(const Cgu::Callback::Callback* cb,
01098             GMainContext* context = 0);
01099 
01100 /**
01101  * This is a version of the fail() utility for use in conjunction with
01102  * the when() methods, which takes a Releaser object for automatic
01103  * disconnection of the callback functor passed as an argument to this
01104  * method if the object having the callback function as a member is
01105  * destroyed.
01106  *
01107  * This method enables a callback to be executed in a glib main loop
01108  * if memory is exhausted and std::bad_alloc was thrown by the thread
01109  * wrapper of Cgu::Thread::Future after calling run() or by
01110  * done_emitter when emitting, or if the thread function represented
01111  * by this Cgu::Thread::Future object threw Cgu::Thread::Exit, exited
01112  * with an uncaught exception deriving from std::exception or was
01113  * cancelled, or any callback connected to done_emitter exited with an
01114  * uncaught exception.  It therefore enables errors to be detected and
01115  * acted on without having a thread wait on the get() method in order
01116  * to test is_error() or is_emitter_error().
01117  *
01118  * This method can be called before or after the run() method has been
01119  * called, and whether or not the thread function represented by this
01120  * Cgu::Thread::Future object has completed.
01121  *
01122  * The documentation for the version of this method which does not
01123  * take a Releaser object gives further details of how this method is
01124  * used.
01125  *
01126  * The glib main loop must have been made thread-safe by a call to
01127  * g_thread_init() before this function is called.
01128  *
01129  * @param cb The 'fail' callback (the callback to be executed if the
01130  * thread function represented by this Cgu::Thread::Future object or a
01131  * done_emitter emission has failed to complete).  Ownership is taken
01132  * of this object, and it will be deleted when it has been finished
01133  * with.
01134  * @param r A Releaser object for automatic disconnection of the
01135  * 'fail' callback if the object of which the callback function is a
01136  * member is destroyed.
01137  * @param context The glib main context of the thread in whose main
01138  * loop the 'fail' callback is to be executed (the default of NULL
01139  * will cause the functor to be executed in the main program loop).
01140  * @exception std::bad_alloc This method might throw std::bad_alloc if
01141  * memory is exhausted and the system throws in that case.  If it does
01142  * so, the 'fail' callback will be disposed of.
01143  * @exception Cgu::Thread::MutexError This method will throw
01144  * Cgu:Thread::MutexError if initialisation of the mutex in a
01145  * SafeEmitterArg object constructed by Cgu::start_timeout() fails.
01146  * If it does so, the 'fail' callback will be disposed of.  (It is
01147  * often not worth checking for this, as it means either memory is
01148  * exhausted or pthread has run out of other resources to create new
01149  * mutexes.)
01150  *
01151  * Since 2.0.2
01152  */
01153   void fail(const Cgu::Callback::Callback* cb,
01154             Cgu::Releaser& r,
01155             GMainContext* context = 0);
01156 
01157 /**
01158  * @return true if the function represented by this
01159  * Cgu::Thread::Future object has finished, either by returning
01160  * normally, by cancellation or by virtue of having thrown
01161  * Cgu::Thread::Exit or some exception derived from std::exception.
01162  * Once this method returns true, then it is guaranteed that the get()
01163  * method will not block (except as incidental to any contention with
01164  * other threads calling get()).  Once this method has returned true
01165  * or get() has unblocked, then the result of is_error() is
01166  * definitive.  This method is thread safe and may be called by any
01167  * thread.  It will not throw.
01168  * @note This method will return true even though any callbacks
01169  * connected to done_emitter are still executing or waiting to
01170  * execute.  From version 2.0.2 the is_emitter_done() method will
01171  * indicate when done_emitter callbacks (if any) have also completed.
01172  */
01173   bool is_done() const;
01174 
01175 /**
01176  * @return true if both the function represented by this
01177  * Cgu::Thread::Future object has finished and any callbacks connected
01178  * to done_emitter have completed.  Once this method returns true,
01179  * then the result of is_emitter_error() is definitive.  This method
01180  * is thread safe and may be called by any thread.  It will not throw.
01181  * @note This method will return true automatically if is_error() and
01182  * is_done() return true, because if the function represented by this
01183  * Cgu::Thread::Future object was cancelled or exited with an uncaught
01184  * exception, done_emitter is never emitted.  In addition, if this
01185  * method returns true, then is_done() must also return true.
01186  *
01187  * Since 2.0.2
01188  */
01189   bool is_emitter_done() const;
01190 
01191 /**
01192  * @return true if (a) a Cgu::Thread::Exit exception has been thrown
01193  * by the function represented by this Cgu::Thread::Future object
01194  * (which will have been consumed by this Cgu::Thread::Future object),
01195  * (b) an exception derived from std::exception has been thrown by
01196  * that function which was not caught in that function (and which will
01197  * also have been consumed by this Cgu::Thread::Future object), (c)
01198  * the worker thread in which that function runs was cancelled in
01199  * mid-course with a call to cancel() or (d) the thread wrapper
01200  * implementing the worker thread in this Cgu::Thread::Future object
01201  * threw and then consumed std::bad_alloc (this is different from the
01202  * run() method throwing std::bad_alloc).  In these cases the value
01203  * obtained by get() will not be valid.  Otherwise this method returns
01204  * false.  The result of this method is definitive once get() has
01205  * unblocked or is_done() returns true.  This method is thread safe
01206  * and may be called by any thread.  It will not throw.
01207  */
01208   bool is_error() const;
01209 
01210 /**
01211  * @return true if an uncaught exception arose in emitting @ref
01212  * DoneEmitterAnchor "done_emitter" when executing callbacks connected
01213  * to it.  Otherwise this method returns false.  The result of this
01214  * method is definitive once is_emitter_done() returns true.  This
01215  * method is thread safe and may be called by any thread.  It will not
01216  * throw.
01217  * @note This method will return false automatically if is_error()
01218  * returns true, because if the function represented by this
01219  * Cgu::Thread::Future object was cancelled or exited with an uncaught
01220  * exception, done_emitter is never emitted.  It follows that if this
01221  * method returns true, is_error() must return false.
01222  */
01223   bool is_emitter_error() const;
01224 
01225 /**
01226  * A Cgu::SafeEmitter object which is emitted when the function
01227  * represented by this Cgu::Thread::Future object finishes correctly
01228  * (that is, the function is not cancelled and does not throw any
01229  * uncaught exceptions).  By itself it does not do too much as it is
01230  * emitted (and connected callbacks execute in) the same worker thread
01231  * immediately after the Future function has completed.  However, any
01232  * thread can connect a Callback object to this Cgu::SafeEmitter
01233  * object and a connected callback can, say, cause another Callback to
01234  * be executed in a thread's main loop using Cgu::Callback::post(),
01235  * and from version 2.0.2 when() methods are provided which will do
01236  * this for users automatically.  Once the run() method has been
01237  * called, this Cgu::Thread::Future object (and so done_emitter) will
01238  * always stay in existence until the function represented by it has
01239  * completed (whether correctly, by cancellation or by a thrown
01240  * exception) and any callbacks connected to the done_emitter object
01241  * have completed, irrespective of whether the intrusive pointer
01242  * returned by the make() methods has gone out of scope.
01243  * @note 1. Cancellation is blocked while the Cgu::SafeEmitter object
01244  * emits and any connected callback executes.
01245  * @note 2. A connected callback can however terminate the worker
01246  * thread by throwing Cgu::Thread::Exit (in which case no subsequent
01247  * callbacks to be executed on that emission will execute either: the
01248  * worker thread will safely terminate and unwind the stack in so
01249  * doing).  In that event, the emitter_error flag will be set.
01250  * @note 3. All other uncaught exceptions which might be thrown by the
01251  * Cgu::SafeEmitter object emitting, or by a connected callback
01252  * function executing, are consumed to retain the integrity of the
01253  * Thread::Future object.  In the event of such an exception being
01254  * thrown, the emitter_error flag will be set.  In summary, the
01255  * emitter_error flag will be set if (a) a callback function throws
01256  * Cgu::Thread::Exit, (b) some other uncaught exception escapes from a
01257  * callback function or (c) Cgu::SafeEmitter::emit() throws
01258  * std::bad_alloc or the copy constructor of a bound argument which is
01259  * not a reference argument has thrown.  If the user knows that the
01260  * callback function does not throw Cgu::Thread::Exit and does not
01261  * allow any other exception to escape, then the cause must be a
01262  * std::bad_alloc memory exception in Cgu::SafeEmitter::emit() or the
01263  * copy constructor of a non-reference bound argument throwing.
01264  * @note 4. An emission is thread safe if the connected callback
01265  * functions are thread safe.
01266  * @anchor DoneEmitterAnchor
01267  */
01268   SafeEmitter done_emitter;
01269 
01270 /* Only has effect if --with-glib-memory-slices-compat or
01271  * --with-glib-memory-slices-no-compat option picked */
01272   CGU_GLIB_MEMORY_SLICES_FUNCS
01273 };
01274 
01275 /**
01276  * A convenience helper function which calls
01277  * Cgu::Thread::Future::make() to obtain a Future object without the
01278  * need to specify the return value of the function represented by the
01279  * new object: that is deduced from the signature of that function.
01280  * This is useful shorthand when also employed with the C++11 'auto'
01281  * keyword.
01282  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01283  * is exhausted and the system throws in that case.  (This exception
01284  * will not be thrown if the library has been installed using the
01285  * --with-glib-memory-slices-no-compat configuration option: instead
01286  * glib will terminate the program if it is unable to obtain memory
01287  * from the operating system.)  It will also throw if the copy
01288  * constructor or assignment operator of a bound argument throws, or
01289  * the default constructor of the return value type of the function
01290  * represented by the new object throws.
01291  *
01292  * Since 2.0.4
01293  */
01294 template <class Obj, class Ret, class... Params, class... Args>
01295 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(Obj& obj,
01296                                                         Ret (Obj::*func)(Params...),
01297                                                         Args&&... args) {
01298   return Cgu::Thread::Future<Ret>::make(obj, func, std::forward<Args>(args)...);
01299 }
01300 
01301 /**
01302  * A convenience helper function which calls
01303  * Cgu::Thread::Future::make() to obtain a Future object without the
01304  * need to specify the return value of the function represented by the
01305  * new object: that is deduced from the signature of that function.
01306  * This is useful shorthand when also employed with the C++11 'auto'
01307  * keyword.
01308  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01309  * is exhausted and the system throws in that case.  (This exception
01310  * will not be thrown if the library has been installed using the
01311  * --with-glib-memory-slices-no-compat configuration option: instead
01312  * glib will terminate the program if it is unable to obtain memory
01313  * from the operating system.)  It will also throw if the copy
01314  * constructor or assignment operator of a bound argument throws, or
01315  * the default constructor of the return value type of the function
01316  * represented by the new object throws.
01317  *
01318  * Since 2.0.4
01319  */
01320 template <class Obj, class Ret, class... Params, class... Args>
01321 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(const Obj& obj,
01322                                                         Ret (Obj::*func)(Params...) const,
01323                                                         Args&&... args) {
01324   return Cgu::Thread::Future<Ret>::make(obj, func, std::forward<Args>(args)...);
01325 }
01326 
01327 /**
01328  * A convenience helper function which calls
01329  * Cgu::Thread::Future::make() to obtain a Future object without the
01330  * need to specify the return value of the function represented by the
01331  * new object: that is deduced from the signature of that function.
01332  * This is useful shorthand when also employed with the C++11 'auto'
01333  * keyword.
01334  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01335  * is exhausted and the system throws in that case.  (This exception
01336  * will not be thrown if the library has been installed using the
01337  * --with-glib-memory-slices-no-compat configuration option: instead
01338  * glib will terminate the program if it is unable to obtain memory
01339  * from the operating system.)  It will also throw if the copy
01340  * constructor or assignment operator of a bound argument throws, or
01341  * the default constructor of the return value type of the function
01342  * represented by the new object throws.
01343  *
01344  * Since 2.0.4
01345  */
01346 template <class Ret, class... Params, class... Args>
01347 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(Ret (*func)(Params...),
01348                                                         Args&&... args) {
01349   return Cgu::Thread::Future<Ret>::make(func, std::forward<Args>(args)...);
01350 }
01351 
01352 /**
01353  * A convenience helper function which calls
01354  * Cgu::Thread::Future::make() to obtain a Future object without the
01355  * need to specify the return value of the function represented by the
01356  * new object: that is deduced from the signature of that function.
01357  * This is useful shorthand when also employed with the C++11 'auto'
01358  * keyword.
01359  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01360  * is exhausted and the system throws in that case.  (This exception
01361  * will not be thrown if the library has been installed using the
01362  * --with-glib-memory-slices-no-compat configuration option: instead
01363  * glib will terminate the program if it is unable to obtain memory
01364  * from the operating system.)  It will also throw if the copy
01365  * constructor or assignment operator of a bound argument throws, or
01366  * the default constructor of the return value type of the function
01367  * represented by the new object throws.
01368  *
01369  * Since 2.0.4
01370  */
01371 template <class Ret>
01372 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(const std::function<Ret(void)>& func) {
01373   return Cgu::Thread::Future<Ret>::make(func);
01374 }
01375 
01376 /**
01377  * A convenience helper function which calls
01378  * Cgu::Thread::Future::make() to obtain a Future object without the
01379  * need to specify the return value of the function represented by the
01380  * new object: that is deduced from the signature of that function.
01381  * This is useful shorthand when also employed with the C++11 'auto'
01382  * keyword.
01383  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01384  * is exhausted and the system throws in that case.  (This exception
01385  * will not be thrown if the library has been installed using the
01386  * --with-glib-memory-slices-no-compat configuration option: instead
01387  * glib will terminate the program if it is unable to obtain memory
01388  * from the operating system.)  It will also throw if the copy
01389  * constructor or assignment operator of a bound argument throws, or
01390  * the default constructor of the return value type of the function
01391  * represented by the new object throws.
01392  *
01393  * Since 2.0.4
01394  */
01395 template <class Ret>
01396 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(std::function<Ret(void)>&& func) {
01397   return Cgu::Thread::Future<Ret>::make(std::move(func));
01398 }
01399 
01400 } // namespace Thread
01401 
01402 } // namespace Cgu
01403 
01404 #include <c++-gtk-utils/future.tpp>
01405 
01406 #endif