cancelable-task.h 6.18 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
  ~CancelableTaskManager();
40 41
  CancelableTaskManager(const CancelableTaskManager&) = delete;
  CancelableTaskManager& operator=(const CancelableTaskManager&) = delete;
42

43 44
  // 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}.
45 46
  // If {Register} is called after {CancelAndWait}, then the task will be
  // aborted immediately.
47 48 49
  // {Register} should only be called by the thread which owns the
  // {CancelableTaskManager}, or by a task which is managed by the
  // {CancelableTaskManager}.
50
  Id Register(Cancelable* task);
51

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

55 56 57 58 59 60 61 62 63 64 65
  // 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();

66 67 68 69 70 71 72
  // 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_; }

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

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

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

  // 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_;

89 90
  bool canceled_;

91
  friend class Cancelable;
92 93
};

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
  virtual ~Cancelable();
100 101
  Cancelable(const Cancelable&) = delete;
  Cancelable& operator=(const Cancelable&) = delete;
ulan's avatar
ulan committed
102

103 104 105 106 107
  // 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.
108
  CancelableTaskManager::Id id() { return id_; }
ulan's avatar
ulan committed
109 110

 protected:
111 112 113 114 115
  // 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.
116 117 118 119 120 121 122 123
  enum Status { kWaiting, kCanceled, kRunning };

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

 private:
  friend class CancelableTaskManager;
124 125 126

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

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

  CancelableTaskManager* const parent_;
  std::atomic<Status> status_{kWaiting};
  const CancelableTaskManager::Id id_;
ulan's avatar
ulan committed
142
};
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);
150 151
  CancelableTask(const CancelableTask&) = delete;
  CancelableTask& operator=(const CancelableTask&) = delete;
ulan's avatar
ulan committed
152 153

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

  virtual void RunInternal() = 0;
};

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

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

  virtual void RunInternal(double deadline_in_seconds) = 0;
};

181 182 183
}  // namespace internal
}  // namespace v8

184
#endif  // V8_TASKS_CANCELABLE_TASK_H_