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