Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef BASE_TASK_RUNNER_H_
      6 #define BASE_TASK_RUNNER_H_
      7 
      8 #include "base/base_export.h"
      9 #include "base/basictypes.h"
     10 #include "base/callback_forward.h"
     11 #include "base/memory/ref_counted.h"
     12 #include "base/time/time.h"
     13 
     14 namespace tracked_objects {
     15 class Location;
     16 } // namespace tracked_objects
     17 
     18 namespace base {
     19 
     20 struct TaskRunnerTraits;
     21 
     22 // A TaskRunner is an object that runs posted tasks (in the form of
     23 // Closure objects).  The TaskRunner interface provides a way of
     24 // decoupling task posting from the mechanics of how each task will be
     25 // run.  TaskRunner provides very weak guarantees as to how posted
     26 // tasks are run (or if they're run at all).  In particular, it only
     27 // guarantees:
     28 //
     29 //   - Posting a task will not run it synchronously.  That is, no
     30 //     Post*Task method will call task.Run() directly.
     31 //
     32 //   - Increasing the delay can only delay when the task gets run.
     33 //     That is, increasing the delay may not affect when the task gets
     34 //     run, or it could make it run later than it normally would, but
     35 //     it won't make it run earlier than it normally would.
     36 //
     37 // TaskRunner does not guarantee the order in which posted tasks are
     38 // run, whether tasks overlap, or whether they're run on a particular
     39 // thread.  Also it does not guarantee a memory model for shared data
     40 // between tasks.  (In other words, you should use your own
     41 // synchronization/locking primitives if you need to share data
     42 // between tasks.)
     43 //
     44 // Implementations of TaskRunner should be thread-safe in that all
     45 // methods must be safe to call on any thread.  Ownership semantics
     46 // for TaskRunners are in general not clear, which is why the
     47 // interface itself is RefCountedThreadSafe.
     48 //
     49 // Some theoretical implementations of TaskRunner:
     50 //
     51 //   - A TaskRunner that uses a thread pool to run posted tasks.
     52 //
     53 //   - A TaskRunner that, for each task, spawns a non-joinable thread
     54 //     to run that task and immediately quit.
     55 //
     56 //   - A TaskRunner that stores the list of posted tasks and has a
     57 //     method Run() that runs each runnable task in random order.
     58 class BASE_EXPORT TaskRunner
     59     : public RefCountedThreadSafe<TaskRunner, TaskRunnerTraits> {
     60  public:
     61   // Posts the given task to be run.  Returns true if the task may be
     62   // run at some point in the future, and false if the task definitely
     63   // will not be run.
     64   //
     65   // Equivalent to PostDelayedTask(from_here, task, 0).
     66   bool PostTask(const tracked_objects::Location& from_here,
     67                 const Closure& task);
     68 
     69   // Like PostTask, but tries to run the posted task only after
     70   // |delay_ms| has passed.
     71   //
     72   // It is valid for an implementation to ignore |delay_ms|; that is,
     73   // to have PostDelayedTask behave the same as PostTask.
     74   virtual bool PostDelayedTask(const tracked_objects::Location& from_here,
     75                                const Closure& task,
     76                                base::TimeDelta delay) = 0;
     77 
     78   // Returns true if the current thread is a thread on which a task
     79   // may be run, and false if no task will be run on the current
     80   // thread.
     81   //
     82   // It is valid for an implementation to always return true, or in
     83   // general to use 'true' as a default value.
     84   virtual bool RunsTasksOnCurrentThread() const = 0;
     85 
     86   // Posts |task| on the current TaskRunner.  On completion, |reply|
     87   // is posted to the thread that called PostTaskAndReply().  Both
     88   // |task| and |reply| are guaranteed to be deleted on the thread
     89   // from which PostTaskAndReply() is invoked.  This allows objects
     90   // that must be deleted on the originating thread to be bound into
     91   // the |task| and |reply| Closures.  In particular, it can be useful
     92   // to use WeakPtr<> in the |reply| Closure so that the reply
     93   // operation can be canceled. See the following pseudo-code:
     94   //
     95   // class DataBuffer : public RefCountedThreadSafe<DataBuffer> {
     96   //  public:
     97   //   // Called to add data into a buffer.
     98   //   void AddData(void* buf, size_t length);
     99   //   ...
    100   // };
    101   //
    102   //
    103   // class DataLoader : public SupportsWeakPtr<DataLoader> {
    104   //  public:
    105   //    void GetData() {
    106   //      scoped_refptr<DataBuffer> buffer = new DataBuffer();
    107   //      target_thread_.message_loop_proxy()->PostTaskAndReply(
    108   //          FROM_HERE,
    109   //          base::Bind(&DataBuffer::AddData, buffer),
    110   //          base::Bind(&DataLoader::OnDataReceived, AsWeakPtr(), buffer));
    111   //    }
    112   //
    113   //  private:
    114   //    void OnDataReceived(scoped_refptr<DataBuffer> buffer) {
    115   //      // Do something with buffer.
    116   //    }
    117   // };
    118   //
    119   //
    120   // Things to notice:
    121   //   * Results of |task| are shared with |reply| by binding a shared argument
    122   //     (a DataBuffer instance).
    123   //   * The DataLoader object has no special thread safety.
    124   //   * The DataLoader object can be deleted while |task| is still running,
    125   //     and the reply will cancel itself safely because it is bound to a
    126   //     WeakPtr<>.
    127   bool PostTaskAndReply(const tracked_objects::Location& from_here,
    128                         const Closure& task,
    129                         const Closure& reply);
    130 
    131  protected:
    132   friend struct TaskRunnerTraits;
    133 
    134   // Only the Windows debug build seems to need this: see
    135   // http://crbug.com/112250.
    136   friend class RefCountedThreadSafe<TaskRunner, TaskRunnerTraits>;
    137 
    138   TaskRunner();
    139   virtual ~TaskRunner();
    140 
    141   // Called when this object should be destroyed.  By default simply
    142   // deletes |this|, but can be overridden to do something else, like
    143   // delete on a certain thread.
    144   virtual void OnDestruct() const;
    145 };
    146 
    147 struct BASE_EXPORT TaskRunnerTraits {
    148   static void Destruct(const TaskRunner* task_runner);
    149 };
    150 
    151 }  // namespace base
    152 
    153 #endif  // BASE_TASK_RUNNER_H_
    154