cancelable-task.h 5.92 KB
Newer Older
1 2 3 4
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#ifndef V8_TASKS_CANCELABLE_TASK_H_
#define V8_TASKS_CANCELABLE_TASK_H_
7

8
#include <atomic>
9
#include <unordered_map>
10

11 12
#include "include/v8-platform.h"
#include "src/base/macros.h"
13
#include "src/base/platform/condition-variable.h"
14
#include "src/common/globals.h"
15 16 17 18

namespace v8 {
namespace internal {

19
class Cancelable;
20 21
class Isolate;

22 23 24 25 26 27 28
// The possible outcomes of trying to abort a job are:
// (1) The task is already finished running or was canceled before and
//     thus has been removed from the manager.
// (2) The task is currently running and cannot be canceled anymore.
// (3) The task is not yet running (or finished) so it is canceled and
//     removed.
enum class TryAbortResult { kTaskRemoved, kTaskRunning, kTaskAborted };
ulan's avatar
ulan committed
29

30 31
// Keeps track of cancelable tasks. It is possible to register and remove tasks
// from any fore- and background task/thread.
32
class V8_EXPORT_PRIVATE CancelableTaskManager {
33
 public:
34
  using Id = uint64_t;
35
  static constexpr Id kInvalidTaskId = 0;
36

37 38
  CancelableTaskManager();

39 40
  ~CancelableTaskManager();

41 42
  // Registers a new cancelable {task}. Returns the unique {id} of the task that
  // can be used to try to abort a task by calling {Abort}.
43 44
  // If {Register} is called after {CancelAndWait}, then the task will be
  // aborted immediately.
45 46 47
  // {Register} should only be called by the thread which owns the
  // {CancelableTaskManager}, or by a task which is managed by the
  // {CancelableTaskManager}.
48
  Id Register(Cancelable* task);
49

50
  // Try to abort running a task identified by {id}.
51
  TryAbortResult TryAbort(Id id);
52

53 54 55 56 57 58 59 60 61 62 63
  // Tries to cancel all remaining registered tasks. The return value indicates
  // whether
  //
  // 1) No tasks were registered (kTaskRemoved), or
  //
  // 2) There is at least one remaining task that couldn't be cancelled
  // (kTaskRunning), or
  //
  // 3) All registered tasks were cancelled (kTaskAborted).
  TryAbortResult TryAbortAll();

64 65 66 67 68 69 70
  // Cancels all remaining registered tasks and waits for tasks that are
  // already running. This disallows subsequent Register calls.
  void CancelAndWait();

  // Returns true of the task manager has been cancelled.
  bool canceled() const { return canceled_; }

71
 private:
72 73
  // Only called by {Cancelable} destructor. The task is done with executing,
  // but needs to be removed.
74
  void RemoveFinishedTask(Id id);
75

76
  // To mitigate the ABA problem, the api refers to tasks through an id.
77
  Id task_id_counter_;
78 79

  // A set of cancelable tasks that are currently registered.
80
  std::unordered_map<Id, Cancelable*> cancelable_tasks_;
81 82 83 84 85 86

  // Mutex and condition variable enabling concurrent register and removing, as
  // well as waiting for background tasks on {CancelAndWait}.
  base::ConditionVariable cancelable_tasks_barrier_;
  base::Mutex mutex_;

87 88
  bool canceled_;

89 90
  friend class Cancelable;

91 92 93
  DISALLOW_COPY_AND_ASSIGN(CancelableTaskManager);
};

94
class V8_EXPORT_PRIVATE Cancelable {
95
 public:
96 97 98
  explicit Cancelable(CancelableTaskManager* parent)
      : parent_(parent), id_(parent->Register(this)) {}

ulan's avatar
ulan committed
99 100
  virtual ~Cancelable();

101 102 103 104 105
  // Never invoke after handing over the task to the platform! The reason is
  // that {Cancelable} is used in combination with {v8::Task} and handed to
  // a platform. This step transfers ownership to the platform, which destroys
  // the task after running it. Since the exact time is not known, we cannot
  // access the object after handing it to a platform.
106
  CancelableTaskManager::Id id() { return id_; }
ulan's avatar
ulan committed
107 108

 protected:
109 110 111 112 113
  // Identifies the state a cancelable task is in:
  // |kWaiting|: The task is scheduled and waiting to be executed. {TryRun} will
  //   succeed.
  // |kCanceled|: The task has been canceled. {TryRun} will fail.
  // |kRunning|: The task is currently running and cannot be canceled anymore.
114 115 116 117 118 119 120 121
  enum Status { kWaiting, kCanceled, kRunning };

  bool TryRun(Status* previous = nullptr) {
    return CompareExchangeStatus(kWaiting, kRunning, previous);
  }

 private:
  friend class CancelableTaskManager;
122 123 124

  // Use {CancelableTaskManager} to abort a task that has not yet been
  // executed.
125
  bool Cancel() { return CompareExchangeStatus(kWaiting, kCanceled); }
126

127 128 129 130
  bool CompareExchangeStatus(Status expected, Status desired,
                             Status* previous = nullptr) {
    // {compare_exchange_strong} updates {expected}.
    bool success = status_.compare_exchange_strong(expected, desired,
131 132
                                                   std::memory_order_acq_rel,
                                                   std::memory_order_acquire);
133 134 135 136 137 138 139
    if (previous) *previous = expected;
    return success;
  }

  CancelableTaskManager* const parent_;
  std::atomic<Status> status_{kWaiting};
  const CancelableTaskManager::Id id_;
140

ulan's avatar
ulan committed
141 142
  DISALLOW_COPY_AND_ASSIGN(Cancelable);
};
143

ulan's avatar
ulan committed
144
// Multiple inheritance can be used because Task is a pure interface.
145 146
class V8_EXPORT_PRIVATE CancelableTask : public Cancelable,
                                         NON_EXPORTED_BASE(public Task) {
ulan's avatar
ulan committed
147
 public:
148
  explicit CancelableTask(Isolate* isolate);
149
  explicit CancelableTask(CancelableTaskManager* manager);
ulan's avatar
ulan committed
150 151

  // Task overrides.
152
  void Run() final {
153
    if (TryRun()) {
154 155 156 157 158 159 160 161 162 163
      RunInternal();
    }
  }

  virtual void RunInternal() = 0;

 private:
  DISALLOW_COPY_AND_ASSIGN(CancelableTask);
};

ulan's avatar
ulan committed
164 165 166
// Multiple inheritance can be used because IdleTask is a pure interface.
class CancelableIdleTask : public Cancelable, public IdleTask {
 public:
167
  explicit CancelableIdleTask(Isolate* isolate);
168
  explicit CancelableIdleTask(CancelableTaskManager* manager);
ulan's avatar
ulan committed
169 170 171

  // IdleTask overrides.
  void Run(double deadline_in_seconds) final {
172
    if (TryRun()) {
ulan's avatar
ulan committed
173 174 175 176 177 178 179 180 181 182
      RunInternal(deadline_in_seconds);
    }
  }

  virtual void RunInternal(double deadline_in_seconds) = 0;

 private:
  DISALLOW_COPY_AND_ASSIGN(CancelableIdleTask);
};

183 184 185
}  // namespace internal
}  // namespace v8

186
#endif  // V8_TASKS_CANCELABLE_TASK_H_