Home | History | Annotate | Download | only in base
      1 /*
      2  * libjingle
      3  * Copyright 2014 Google Inc.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions are met:
      7  *
      8  *  1. Redistributions of source code must retain the above copyright notice,
      9  *     this list of conditions and the following disclaimer.
     10  *  2. Redistributions in binary form must reproduce the above copyright notice,
     11  *     this list of conditions and the following disclaimer in the documentation
     12  *     and/or other materials provided with the distribution.
     13  *  3. The name of the author may not be used to endorse or promote products
     14  *     derived from this software without specific prior written permission.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
     17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
     19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #ifndef TALK_BASE_ASYNCINVOKER_H_
     29 #define TALK_BASE_ASYNCINVOKER_H_
     30 
     31 #include "talk/base/asyncinvoker-inl.h"
     32 #include "talk/base/bind.h"
     33 #include "talk/base/sigslot.h"
     34 #include "talk/base/scopedptrcollection.h"
     35 #include "talk/base/thread.h"
     36 
     37 namespace talk_base {
     38 
     39 // Invokes function objects (aka functors) asynchronously on a Thread, and
     40 // owns the lifetime of calls (ie, when this object is destroyed, calls in
     41 // flight are cancelled). AsyncInvoker can optionally execute a user-specified
     42 // function when the asynchronous call is complete, or operates in
     43 // fire-and-forget mode otherwise.
     44 //
     45 // AsyncInvoker does not own the thread it calls functors on.
     46 //
     47 // A note about async calls and object lifetimes: users should
     48 // be mindful of object lifetimes when calling functions asynchronously and
     49 // ensure objects used by the function _cannot_ be deleted between the
     50 // invocation and execution of the functor. AsyncInvoker is designed to
     51 // help: any calls in flight will be cancelled when the AsyncInvoker used to
     52 // make the call is destructed, and any calls executing will be allowed to
     53 // complete before AsyncInvoker destructs.
     54 //
     55 // The easiest way to ensure lifetimes are handled correctly is to create a
     56 // class that owns the Thread and AsyncInvoker objects, and then call its
     57 // methods asynchronously as needed.
     58 //
     59 // Example:
     60 //   class MyClass {
     61 //    public:
     62 //     void FireAsyncTaskWithResult(Thread* thread, int x) {
     63 //       // Specify a callback to get the result upon completion.
     64 //       invoker_.AsyncInvoke<int>(
     65 //           thread, Bind(&MyClass::AsyncTaskWithResult, this, x),
     66 //           &MyClass::OnTaskComplete, this);
     67 //     }
     68 //     void FireAnotherAsyncTask(Thread* thread) {
     69 //       // No callback specified means fire-and-forget.
     70 //       invoker_.AsyncInvoke<void>(
     71 //           thread, Bind(&MyClass::AnotherAsyncTask, this));
     72 //
     73 //    private:
     74 //     int AsyncTaskWithResult(int x) {
     75 //       // Some long running process...
     76 //       return x * x;
     77 //     }
     78 //     void AnotherAsyncTask() {
     79 //       // Some other long running process...
     80 //     }
     81 //     void OnTaskComplete(int result) { result_ = result; }
     82 //
     83 //     AsyncInvoker invoker_;
     84 //     int result_;
     85 //   };
     86 class AsyncInvoker : public MessageHandler {
     87  public:
     88   AsyncInvoker();
     89   virtual ~AsyncInvoker();
     90 
     91   // Call |functor| asynchronously on |thread|, with no callback upon
     92   // completion. Returns immediately.
     93   template <class ReturnT, class FunctorT>
     94   void AsyncInvoke(Thread* thread,
     95                    const FunctorT& functor,
     96                    uint32 id = 0) {
     97     AsyncClosure* closure =
     98         new RefCountedObject<FireAndForgetAsyncClosure<FunctorT> >(functor);
     99     DoInvoke(thread, closure, id);
    100   }
    101 
    102   // Call |functor| asynchronously on |thread|, calling |callback| when done.
    103   template <class ReturnT, class FunctorT, class HostT>
    104   void AsyncInvoke(Thread* thread,
    105                    const FunctorT& functor,
    106                    void (HostT::*callback)(ReturnT),
    107                    HostT* callback_host,
    108                    uint32 id = 0) {
    109     AsyncClosure* closure =
    110         new RefCountedObject<NotifyingAsyncClosure<ReturnT, FunctorT, HostT> >(
    111             this, Thread::Current(), functor, callback, callback_host);
    112     DoInvoke(thread, closure, id);
    113   }
    114 
    115   // Call |functor| asynchronously on |thread|, calling |callback| when done.
    116   // Overloaded for void return.
    117   template <class ReturnT, class FunctorT, class HostT>
    118   void AsyncInvoke(Thread* thread,
    119                    const FunctorT& functor,
    120                    void (HostT::*callback)(),
    121                    HostT* callback_host,
    122                    uint32 id = 0) {
    123     AsyncClosure* closure =
    124         new RefCountedObject<NotifyingAsyncClosure<void, FunctorT, HostT> >(
    125             this, Thread::Current(), functor, callback, callback_host);
    126     DoInvoke(thread, closure, id);
    127   }
    128 
    129   // Synchronously execute on |thread| all outstanding calls we own
    130   // that are pending on |thread|, and wait for calls to complete
    131   // before returning. Optionally filter by message id.
    132   // The destructor will not wait for outstanding calls, so if that
    133   // behavior is desired, call Flush() before destroying this object.
    134   void Flush(Thread* thread, uint32 id = MQID_ANY);
    135 
    136   // Signaled when this object is destructed.
    137   sigslot::signal0<> SignalInvokerDestroyed;
    138 
    139  private:
    140   virtual void OnMessage(Message* msg);
    141   void DoInvoke(Thread* thread, AsyncClosure* closure, uint32 id);
    142 
    143   bool destroying_;
    144 
    145   DISALLOW_COPY_AND_ASSIGN(AsyncInvoker);
    146 };
    147 
    148 }  // namespace talk_base
    149 
    150 
    151 #endif  // TALK_BASE_ASYNCINVOKER_H_
    152