c++-gtk-utils
future.h
Go to the documentation of this file.
00001 /* Copyright (C) 2010 to 2012 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    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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::make_future()
00249  *   auto f3 =
00250  *     Thread::make_future(obj, static_cast<int(Numbers::*)(int)>(&Numbers::calc), i);
00251  *   auto f4 =
00252  *     Thread::make_future(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  * If glib < 2.32 is used, the glib main loop must have been made
00859  * thread-safe by a call to g_thread_init() before this function is
00860  * called.  glib >= 2.32 does not require g_thread_init() to be called
00861  * in order to be thread safe.
00862  *
00863  * @param cb The 'when' callback (the callback to be executed when the
00864  * function represented by this Cgu::Thread::Future object has
00865  * successfully completed).  Ownership is taken of this object, and it
00866  * will be deleted when it has been finished with.
00867  * @param priority The priority to be given to the 'when' callback in
00868  * the main loop after the thread function represented by this
00869  * Cgu::Thread::Future object has successfully completed.  In
00870  * ascending order of priorities, priorities are G_PRIORITY_LOW,
00871  * G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT
00872  * and G_PRIORITY_HIGH. The default is G_PRIORITY_DEFAULT.  This
00873  * determines the order in which the callback will appear in the event
00874  * list in the main loop, not the priority which the OS will adopt.
00875  * @param context The glib main context of the thread in whose main
00876  * loop the 'when' callback is to be executed (the default of NULL
00877  * will cause the callback to be executed in the main program loop).
00878  * @return The internal dispatching callback created by this method
00879  * and connected to done_emitter.  It is made available as a return
00880  * value so that if wanted it can be disconnected programmatically
00881  * from done_emitter, or block()/unblock() can be called on it (but if
00882  * that is to be done, it must be done before the thread function
00883  * represented by this Cgu::Thread::Future object has completed in
00884  * order for it to be effective).
00885  * @exception Cgu::Thread::FutureWhenError This method will throw
00886  * Cgu::Thread::FutureWhenError if it is called after the thread
00887  * function represented by this Cgu::Thread::Future object has
00888  * completed.  If it does so, the 'when' callback will be disposed of.
00889  * @exception std::bad_alloc This method might throw std::bad_alloc if
00890  * memory is exhausted and the system throws in that case.  If it does
00891  * so, the 'when' callback will be disposed of.
00892  * @note The return value of the function represented by the
00893  * Cgu::Thread::Future object is passed as an argument to the callback
00894  * by const reference.  This should be taken into account if the
00895  * return value is of class type and other threads might access it
00896  * concurrently via the get() method by const reference (that is,
00897  * without copying it), where any of that return value's const methods
00898  * are not thread safe.
00899  *
00900  * Since 2.0.2
00901  */
00902   Cgu::Callback::SafeFunctor when(const Cgu::Callback::CallbackArg<const Val&>* cb,
00903                                   gint priority = G_PRIORITY_DEFAULT,
00904                                   GMainContext* context = 0);
00905 
00906 /**
00907  * This is a version of the utility enabling the value returned by the
00908  * thread function represented by this Cgu::Thread::Future object to
00909  * be dealt with asynchronously, which takes a Releaser object for
00910  * automatic disconnection of the callback passed as an argument to
00911  * this method (referred to below as the 'when' callback), if the
00912  * object having the 'when' callback function as a member is
00913  * destroyed.  For this to be race free, the lifetime of that object
00914  * must be controlled by the thread in whose main loop the 'when'
00915  * callback will execute.
00916  *
00917  * If the 'when' callback has not been released, this method causes it
00918  * to be executed by a thread's main loop if and when the thread
00919  * function represented by this Cgu::Thread::Future object finishes
00920  * correctly - the 'when' callback is passed that thread function's
00921  * return value when it is invoked.  This method is thread safe, and
00922  * may be called by any thread.
00923  *
00924  * This functionality is implemented by connecting an internal
00925  * dispatching callback to the done_emitter object.
00926  *
00927  * The 'when' callback should take a single unbound argument
00928  * comprising a const reference to the return type of the thread
00929  * function represented by this Cgu::Thread::Future object.  (So, in
00930  * the case of a Future<int> object, the callback function should take
00931  * a const int& argument as the unbound argument.)  The 'when'
00932  * callback can have any number of bound arguments, except that a
00933  * bound argument may not include a copy of this Cgu::Thread::Future
00934  * object held by intrusive pointer as returned by the make() methods
00935  * (that would result in this Cgu::Thread::Future object owning, via
00936  * done_emitter, a reference to itself and so become incapable of
00937  * being freed).  The 'when' callback may, however, take a pointer to
00938  * this Cgu::Thread::Future object, as obtained by the
00939  * Cgu::IntrusivePtr::get() method, because this Cgu::Thread::Future
00940  * object is guaranteed to remain in existence until the callback has
00941  * completed executing.
00942  *
00943  * This method cannot be called after the thread function represented
00944  * by this Cgu::Thread::Future object has completed (either
00945  * successfully or unsuccessfully) so that is_done() would return
00946  * true, and if this is attempted a Cgu::Thread::FutureWhenError
00947  * exception will be thrown.  Therefore, generally this method should
00948  * be called before the run() method has been called.
00949  *
00950  * The documentation for the version of this method which does not
00951  * take a Releaser object gives further details of how this method is
00952  * used.
00953  *
00954  * If glib < 2.32 is used, the glib main loop must have been made
00955  * thread-safe by a call to g_thread_init() before this function is
00956  * called.  glib >= 2.32 does not require g_thread_init() to be called
00957  * in order to be thread safe.
00958  *
00959  * @param cb The 'when' callback (the callback to be executed when the
00960  * function represented by this Cgu::Thread::Future object has
00961  * successfully completed).  Ownership is taken of this object, and it
00962  * will be deleted when it has been finished with.
00963  * @param r A Releaser object for automatic disconnection of the
00964  * 'when' callback if the object of which the callback function is a
00965  * member is destroyed.
00966  * @param priority The priority to be given to the 'when' callback in
00967  * the main loop after the thread function represented by this
00968  * Cgu::Thread::Future object has successfully completed.  In
00969  * ascending order of priorities, priorities are G_PRIORITY_LOW,
00970  * G_PRIORITY_DEFAULT_IDLE, G_PRIORITY_HIGH_IDLE, G_PRIORITY_DEFAULT
00971  * and G_PRIORITY_HIGH. The default is G_PRIORITY_DEFAULT.  This
00972  * determines the order in which the callback will appear in the event
00973  * list in the main loop, not the priority which the OS will adopt.
00974  * @param context The glib main context of the thread in whose main
00975  * loop the 'when' callback is to be executed (the default of NULL
00976  * will cause the callback to be executed in the main program loop).
00977  * @return The internal dispatching callback created by this method
00978  * and connected to done_emitter.  It is made available as a return
00979  * value so that if wanted it can be disconnected programmatically
00980  * from done_emitter, or block()/unblock() can be called on it (but if
00981  * that is to be done, it must be done before the thread function
00982  * represented by this Cgu::Thread::Future object has completed in
00983  * order for it to be effective).
00984  * @exception Cgu::Thread::FutureWhenError This method will throw
00985  * Cgu::Thread::FutureWhenError if it is called after the thread
00986  * function represented by this Cgu::Thread::Future object has
00987  * completed.  If it does so, the 'when' callback will be disposed of.
00988  * @exception std::bad_alloc This method might throw std::bad_alloc if
00989  * memory is exhausted and the system throws in that case.  If it does
00990  * so, the 'when' callback will be disposed of.
00991  * @exception Cgu::Thread::MutexError This method will throw
00992  * Cgu:Thread::MutexError if initialisation of the mutex in a
00993  * SafeEmitterArg object constructed by this method fails.  If it does
00994  * so, the 'when' callback will be disposed of.  (It is often not
00995  * worth checking for this, as it means either memory is exhausted or
00996  * pthread has run out of other resources to create new mutexes.)
00997  * @note The return value of the function represented by the
00998  * Cgu::Thread::Future object is passed as an argument to the callback
00999  * by const reference.  This should be taken into account if the
01000  * return value is of class type and other threads might access it
01001  * concurrently via the get() method by const reference (that is,
01002  * without copying it), where any of that return value's const methods
01003  * are not thread safe.
01004  *
01005  * Since 2.0.2
01006  */
01007   Cgu::Callback::SafeFunctor when(const Cgu::Callback::CallbackArg<const Val&>* cb,
01008                                   Cgu::Releaser& r,
01009                                   gint priority = G_PRIORITY_DEFAULT,
01010                                   GMainContext* context = 0);
01011 
01012 /**
01013  * A utility intended to be used where relevant in conjunction with
01014  * the when() methods.  It enables a callback to be executed in a glib
01015  * main loop (referred to below as the 'fail' callback) if memory is
01016  * exhausted and std::bad_alloc was thrown by the thread wrapper of
01017  * Cgu::Thread::Future after calling run() or by done_emitter when
01018  * emitting, or if the thread function represented by this
01019  * Cgu::Thread::Future object threw Cgu::Thread::Exit, exited with an
01020  * uncaught exception deriving from std::exception or was cancelled,
01021  * or any callback connected to done_emitter exited with an uncaught
01022  * exception.  It therefore enables errors to be detected and acted on
01023  * without having a thread wait on the get() method in order to test
01024  * is_error() or is_emitter_error().
01025  *
01026  * It is implemented by attaching a timeout to the main loop which
01027  * polls at 100 millisecond intervals and tests is_done()/is_error()
01028  * and is_emitter_done()/is_emitter_error().  The timeout is
01029  * automatically removed by the implementation once it has been
01030  * detected that an error has occurred and the 'fail' callback is
01031  * executed, or if the thread function represented by this Cgu::Future
01032  * object and all done_emitter emissions (including execution of any
01033  * 'when' callback) have completed successfully.
01034  *
01035  * This method can be called before or after the run() method has been
01036  * called, and whether or not the thread function represented by this
01037  * Cgu::Thread::Future object has completed.
01038  *
01039  * Once this method has been called, this Cgu::Thread::Future object
01040  * will always stay in existence until the timeout has been
01041  * automatically removed by the implementation.  Accordingly it is
01042  * safe to use this method even if the intrusive pointer object
01043  * returned by the make() methods will go out of scope before the
01044  * 'fail' callback has executed: the callback will execute correctly
01045  * irrespective of that.
01046  *
01047  * This method does not have a priority argument: as a polling timeout
01048  * is created, a particular priority will normally have no
01049  * significance (in fact, the 'fail' callback will execute in the main
01050  * loop with a priority of G_PRIORITY_DEFAULT).  If in a special case
01051  * a different polling interval than 100 milliseconds or a different
01052  * priority is required, users can attach their own polling timeouts
01053  * to a main loop and carry out the tests by hand.
01054  *
01055  * Four other points should be noted.  First, if as well as the when()
01056  * method being called some other callback has been connected to
01057  * done_emitter, and that other callback throws, the 'fail' callback
01058  * will execute.  Therefore, if the particular program design requires
01059  * that the 'fail' callback should only execute if the thread function
01060  * represented by this Cgu::Thread::Future object did not complete
01061  * successfully or emitting the 'when' callback failed, no other
01062  * callbacks which throw should be connected to done_emitter.
01063  *
01064  * Secondly, as mentioned in the documentation on the when() method,
01065  * if the 'when' callback exits with an uncaught exception upon being
01066  * executed by the main loop or has a non-reference bound argument
01067  * whose copy constructor throws when it executes, the 'fail' callback
01068  * will not execute (the exception will have been consumed internally
01069  * in order to protect the main loop and a g_critical message issued).
01070  *
01071  * Thirdly, avoid if possible having the 'fail' callback represent a
01072  * function which might throw or which has a non-reference bound
01073  * argument whose copy constructor might throw (such an exception
01074  * would be consumed internally in order to protect the main loop and
01075  * a g_critical message issued, but no other error indication apart
01076  * from the g_critical message will be provided).
01077  *
01078  * Fourthly, unlike the 'when' callback, a copy of this
01079  * Cgu::Thread::Future object held by intrusive pointer as returned by
01080  * the make() methods may safely be bound to the 'fail' callback,
01081  * which would enable the 'fail' callback to determine whether it is
01082  * is_error() or is_emitter_error() which returns false.
01083  *
01084  * If glib < 2.32 is used, the glib main loop must have been made
01085  * thread-safe by a call to g_thread_init() before this function is
01086  * called.  glib >= 2.32 does not require g_thread_init() to be called
01087  * in order to be thread safe.
01088  *
01089  * @param cb The 'fail' callback (the callback to be executed if the
01090  * thread function represented by this Cgu::Thread::Future object or a
01091  * done_emitter emission has failed to complete).  Ownership is taken
01092  * of this object, and it will be deleted when it has been finished
01093  * with.
01094  * @param context The glib main context of the thread in whose main
01095  * loop the 'fail' callback is to be executed (the default of NULL
01096  * will cause the functor to be executed in the main program loop).
01097  * @exception std::bad_alloc This method might throw std::bad_alloc if
01098  * memory is exhausted and the system throws in that case.  If it does
01099  * so, the 'fail' callback will be disposed of.
01100  *
01101  * Since 2.0.2
01102  */
01103   void fail(const Cgu::Callback::Callback* cb,
01104             GMainContext* context = 0);
01105 
01106 /**
01107  * This is a version of the fail() utility for use in conjunction with
01108  * the when() methods, which takes a Releaser object for automatic
01109  * disconnection of the callback functor passed as an argument to this
01110  * method if the object having the callback function as a member is
01111  * destroyed.
01112  *
01113  * This method enables a callback to be executed in a glib main loop
01114  * if memory is exhausted and std::bad_alloc was thrown by the thread
01115  * wrapper of Cgu::Thread::Future after calling run() or by
01116  * done_emitter when emitting, or if the thread function represented
01117  * by this Cgu::Thread::Future object threw Cgu::Thread::Exit, exited
01118  * with an uncaught exception deriving from std::exception or was
01119  * cancelled, or any callback connected to done_emitter exited with an
01120  * uncaught exception.  It therefore enables errors to be detected and
01121  * acted on without having a thread wait on the get() method in order
01122  * to test is_error() or is_emitter_error().
01123  *
01124  * This method can be called before or after the run() method has been
01125  * called, and whether or not the thread function represented by this
01126  * Cgu::Thread::Future object has completed.
01127  *
01128  * The documentation for the version of this method which does not
01129  * take a Releaser object gives further details of how this method is
01130  * used.
01131  *
01132  * If glib < 2.32 is used, the glib main loop must have been made
01133  * thread-safe by a call to g_thread_init() before this function is
01134  * called.  glib >= 2.32 does not require g_thread_init() to be called
01135  * in order to be thread safe.
01136  *
01137  * @param cb The 'fail' callback (the callback to be executed if the
01138  * thread function represented by this Cgu::Thread::Future object or a
01139  * done_emitter emission has failed to complete).  Ownership is taken
01140  * of this object, and it will be deleted when it has been finished
01141  * with.
01142  * @param r A Releaser object for automatic disconnection of the
01143  * 'fail' callback if the object of which the callback function is a
01144  * member is destroyed.
01145  * @param context The glib main context of the thread in whose main
01146  * loop the 'fail' callback is to be executed (the default of NULL
01147  * will cause the functor to be executed in the main program loop).
01148  * @exception std::bad_alloc This method might throw std::bad_alloc if
01149  * memory is exhausted and the system throws in that case.  If it does
01150  * so, the 'fail' callback will be disposed of.
01151  * @exception Cgu::Thread::MutexError This method will throw
01152  * Cgu:Thread::MutexError if initialisation of the mutex in a
01153  * SafeEmitterArg object constructed by Cgu::start_timeout() fails.
01154  * If it does so, the 'fail' callback will be disposed of.  (It is
01155  * often not worth checking for this, as it means either memory is
01156  * exhausted or pthread has run out of other resources to create new
01157  * mutexes.)
01158  *
01159  * Since 2.0.2
01160  */
01161   void fail(const Cgu::Callback::Callback* cb,
01162             Cgu::Releaser& r,
01163             GMainContext* context = 0);
01164 
01165 /**
01166  * @return true if the function represented by this
01167  * Cgu::Thread::Future object has finished, either by returning
01168  * normally, by cancellation or by virtue of having thrown
01169  * Cgu::Thread::Exit or some exception derived from std::exception.
01170  * Once this method returns true, then it is guaranteed that the get()
01171  * method will not block (except as incidental to any contention with
01172  * other threads calling get()).  Once this method has returned true
01173  * or get() has unblocked, then the result of is_error() is
01174  * definitive.  This method is thread safe and may be called by any
01175  * thread.  It will not throw.
01176  * @note This method will return true even though any callbacks
01177  * connected to done_emitter are still executing or waiting to
01178  * execute.  From version 2.0.2 the is_emitter_done() method will
01179  * indicate when done_emitter callbacks (if any) have also completed.
01180  */
01181   bool is_done() const;
01182 
01183 /**
01184  * @return true if both the function represented by this
01185  * Cgu::Thread::Future object has finished and any callbacks connected
01186  * to done_emitter have completed.  Once this method returns true,
01187  * then the result of is_emitter_error() is definitive.  This method
01188  * is thread safe and may be called by any thread.  It will not throw.
01189  * @note This method will return true automatically if is_error() and
01190  * is_done() return true, because if the function represented by this
01191  * Cgu::Thread::Future object was cancelled or exited with an uncaught
01192  * exception, done_emitter is never emitted.  In addition, if this
01193  * method returns true, then is_done() must also return true.
01194  *
01195  * Since 2.0.2
01196  */
01197   bool is_emitter_done() const;
01198 
01199 /**
01200  * @return true if (a) a Cgu::Thread::Exit exception has been thrown
01201  * by the function represented by this Cgu::Thread::Future object
01202  * (which will have been consumed by this Cgu::Thread::Future object),
01203  * (b) an exception derived from std::exception has been thrown by
01204  * that function which was not caught in that function (and which will
01205  * also have been consumed by this Cgu::Thread::Future object), (c)
01206  * the worker thread in which that function runs was cancelled in
01207  * mid-course with a call to cancel() or (d) the thread wrapper
01208  * implementing the worker thread in this Cgu::Thread::Future object
01209  * threw and then consumed std::bad_alloc (this is different from the
01210  * run() method throwing std::bad_alloc).  In these cases the value
01211  * obtained by get() will not be valid.  Otherwise this method returns
01212  * false.  The result of this method is definitive once get() has
01213  * unblocked or is_done() returns true.  This method is thread safe
01214  * and may be called by any thread.  It will not throw.
01215  */
01216   bool is_error() const;
01217 
01218 /**
01219  * @return true if an uncaught exception arose in emitting @ref
01220  * DoneEmitterAnchor "done_emitter" when executing callbacks connected
01221  * to it.  Otherwise this method returns false.  The result of this
01222  * method is definitive once is_emitter_done() returns true.  This
01223  * method is thread safe and may be called by any thread.  It will not
01224  * throw.
01225  * @note This method will return false automatically if is_error()
01226  * returns true, because if the function represented by this
01227  * Cgu::Thread::Future object was cancelled or exited with an uncaught
01228  * exception, done_emitter is never emitted.  It follows that if this
01229  * method returns true, is_error() must return false.
01230  */
01231   bool is_emitter_error() const;
01232 
01233 /**
01234  * A Cgu::SafeEmitter object which is emitted when the function
01235  * represented by this Cgu::Thread::Future object finishes correctly
01236  * (that is, the function is not cancelled and does not throw any
01237  * uncaught exceptions).  By itself it does not do too much as it is
01238  * emitted (and connected callbacks execute in) the same worker thread
01239  * immediately after the Future function has completed.  However, any
01240  * thread can connect a Callback object to this Cgu::SafeEmitter
01241  * object and a connected callback can, say, cause another Callback to
01242  * be executed in a thread's main loop using Cgu::Callback::post(),
01243  * and from version 2.0.2 when() methods are provided which will do
01244  * this for users automatically.  Once the run() method has been
01245  * called, this Cgu::Thread::Future object (and so done_emitter) will
01246  * always stay in existence until the function represented by it has
01247  * completed (whether correctly, by cancellation or by a thrown
01248  * exception) and any callbacks connected to the done_emitter object
01249  * have completed, irrespective of whether the intrusive pointer
01250  * returned by the make() methods has gone out of scope.
01251  * @note 1. Cancellation is blocked while the Cgu::SafeEmitter object
01252  * emits and any connected callback executes.
01253  * @note 2. A connected callback can however terminate the worker
01254  * thread by throwing Cgu::Thread::Exit (in which case no subsequent
01255  * callbacks to be executed on that emission will execute either: the
01256  * worker thread will safely terminate and unwind the stack in so
01257  * doing).  In that event, the emitter_error flag will be set.
01258  * @note 3. All other uncaught exceptions which might be thrown by the
01259  * Cgu::SafeEmitter object emitting, or by a connected callback
01260  * function executing, are consumed to retain the integrity of the
01261  * Thread::Future object.  In the event of such an exception being
01262  * thrown, the emitter_error flag will be set.  In summary, the
01263  * emitter_error flag will be set if (a) a callback function throws
01264  * Cgu::Thread::Exit, (b) some other uncaught exception escapes from a
01265  * callback function or (c) Cgu::SafeEmitter::emit() throws
01266  * std::bad_alloc or the copy constructor of a bound argument which is
01267  * not a reference argument has thrown.  If the user knows that the
01268  * callback function does not throw Cgu::Thread::Exit and does not
01269  * allow any other exception to escape, then the cause must be a
01270  * std::bad_alloc memory exception in Cgu::SafeEmitter::emit() or the
01271  * copy constructor of a non-reference bound argument throwing.
01272  * @note 4. An emission is thread safe if the connected callback
01273  * functions are thread safe.
01274  * @anchor DoneEmitterAnchor
01275  */
01276   SafeEmitter done_emitter;
01277 
01278 /* Only has effect if --with-glib-memory-slices-compat or
01279  * --with-glib-memory-slices-no-compat option picked */
01280   CGU_GLIB_MEMORY_SLICES_FUNCS
01281 };
01282 
01283 /**
01284  * A convenience helper function which calls
01285  * Cgu::Thread::Future::make() to obtain a Future object without the
01286  * need to specify the return value of the function represented by the
01287  * new object: that is deduced from the signature of that function.
01288  * This is useful shorthand when also employed with the C++11 'auto'
01289  * keyword.
01290  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01291  * is exhausted and the system throws in that case.  (This exception
01292  * will not be thrown if the library has been installed using the
01293  * --with-glib-memory-slices-no-compat configuration option: instead
01294  * glib will terminate the program if it is unable to obtain memory
01295  * from the operating system.)  It will also throw if the copy
01296  * constructor or assignment operator of a bound argument throws, or
01297  * the default constructor of the return value type of the function
01298  * represented by the new object throws.
01299  *
01300  * Since 2.0.4
01301  */
01302 template <class Obj, class Ret, class... Params, class... Args>
01303 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(Obj& obj,
01304                                                         Ret (Obj::*func)(Params...),
01305                                                         Args&&... args) {
01306   return Cgu::Thread::Future<Ret>::make(obj, func, std::forward<Args>(args)...);
01307 }
01308 
01309 /**
01310  * A convenience helper function which calls
01311  * Cgu::Thread::Future::make() to obtain a Future object without the
01312  * need to specify the return value of the function represented by the
01313  * new object: that is deduced from the signature of that function.
01314  * This is useful shorthand when also employed with the C++11 'auto'
01315  * keyword.
01316  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01317  * is exhausted and the system throws in that case.  (This exception
01318  * will not be thrown if the library has been installed using the
01319  * --with-glib-memory-slices-no-compat configuration option: instead
01320  * glib will terminate the program if it is unable to obtain memory
01321  * from the operating system.)  It will also throw if the copy
01322  * constructor or assignment operator of a bound argument throws, or
01323  * the default constructor of the return value type of the function
01324  * represented by the new object throws.
01325  *
01326  * Since 2.0.4
01327  */
01328 template <class Obj, class Ret, class... Params, class... Args>
01329 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(const Obj& obj,
01330                                                         Ret (Obj::*func)(Params...) const,
01331                                                         Args&&... args) {
01332   return Cgu::Thread::Future<Ret>::make(obj, func, std::forward<Args>(args)...);
01333 }
01334 
01335 /**
01336  * A convenience helper function which calls
01337  * Cgu::Thread::Future::make() to obtain a Future object without the
01338  * need to specify the return value of the function represented by the
01339  * new object: that is deduced from the signature of that function.
01340  * This is useful shorthand when also employed with the C++11 'auto'
01341  * keyword.
01342  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01343  * is exhausted and the system throws in that case.  (This exception
01344  * will not be thrown if the library has been installed using the
01345  * --with-glib-memory-slices-no-compat configuration option: instead
01346  * glib will terminate the program if it is unable to obtain memory
01347  * from the operating system.)  It will also throw if the copy
01348  * constructor or assignment operator of a bound argument throws, or
01349  * the default constructor of the return value type of the function
01350  * represented by the new object throws.
01351  *
01352  * Since 2.0.4
01353  */
01354 template <class Ret, class... Params, class... Args>
01355 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(Ret (*func)(Params...),
01356                                                         Args&&... args) {
01357   return Cgu::Thread::Future<Ret>::make(func, std::forward<Args>(args)...);
01358 }
01359 
01360 /**
01361  * A convenience helper function which calls
01362  * Cgu::Thread::Future::make() to obtain a Future object without the
01363  * need to specify the return value of the function represented by the
01364  * new object: that is deduced from the signature of that function.
01365  * This is useful shorthand when also employed with the C++11 'auto'
01366  * keyword.
01367  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01368  * is exhausted and the system throws in that case.  (This exception
01369  * will not be thrown if the library has been installed using the
01370  * --with-glib-memory-slices-no-compat configuration option: instead
01371  * glib will terminate the program if it is unable to obtain memory
01372  * from the operating system.)  It will also throw if the copy
01373  * constructor or assignment operator of a bound argument throws, or
01374  * the default constructor of the return value type of the function
01375  * represented by the new object throws.
01376  *
01377  * Since 2.0.4
01378  */
01379 template <class Ret>
01380 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(const std::function<Ret(void)>& func) {
01381   return Cgu::Thread::Future<Ret>::make(func);
01382 }
01383 
01384 /**
01385  * A convenience helper function which calls
01386  * Cgu::Thread::Future::make() to obtain a Future object without the
01387  * need to specify the return value of the function represented by the
01388  * new object: that is deduced from the signature of that function.
01389  * This is useful shorthand when also employed with the C++11 'auto'
01390  * keyword.
01391  * @exception std::bad_alloc It might throw std::bad_alloc if memory
01392  * is exhausted and the system throws in that case.  (This exception
01393  * will not be thrown if the library has been installed using the
01394  * --with-glib-memory-slices-no-compat configuration option: instead
01395  * glib will terminate the program if it is unable to obtain memory
01396  * from the operating system.)  It will also throw if the copy
01397  * constructor or assignment operator of a bound argument throws, or
01398  * the default constructor of the return value type of the function
01399  * represented by the new object throws.
01400  *
01401  * Since 2.0.4
01402  */
01403 template <class Ret>
01404 Cgu::IntrusivePtr<Cgu::Thread::Future<Ret>> make_future(std::function<Ret(void)>&& func) {
01405   return Cgu::Thread::Future<Ret>::make(std::move(func));
01406 }
01407 
01408 } // namespace Thread
01409 
01410 } // namespace Cgu
01411 
01412 #include <c++-gtk-utils/future.tpp>
01413 
01414 #endif