cancelable-task.h 5.89 KB
Newer Older
1 2 3 4 5 6 7
// 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.

#ifndef V8_CANCELABLE_TASK_H_
#define V8_CANCELABLE_TASK_H_

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/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 35
  using Id = uint64_t;

36 37
  CancelableTaskManager();

38 39
  ~CancelableTaskManager();

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

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

52 53 54 55 56 57 58 59 60 61 62
  // 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();

63 64 65 66 67 68 69
  // 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_; }

70
 private:
71 72
  static constexpr Id kInvalidTaskId = 0;

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

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

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

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

88 89
  bool canceled_;

90 91
  friend class Cancelable;

92 93 94
  DISALLOW_COPY_AND_ASSIGN(CancelableTaskManager);
};

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

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

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

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

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

 private:
  friend class CancelableTaskManager;
123 124 125

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

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

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

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

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

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

  virtual void RunInternal() = 0;

 private:
  DISALLOW_COPY_AND_ASSIGN(CancelableTask);
};

ulan's avatar
ulan committed
165 166 167
// Multiple inheritance can be used because IdleTask is a pure interface.
class CancelableIdleTask : public Cancelable, public IdleTask {
 public:
168
  explicit CancelableIdleTask(Isolate* isolate);
169
  explicit CancelableIdleTask(CancelableTaskManager* manager);
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 181 182 183
      RunInternal(deadline_in_seconds);
    }
  }

  virtual void RunInternal(double deadline_in_seconds) = 0;

 private:
  DISALLOW_COPY_AND_ASSIGN(CancelableIdleTask);
};

184 185 186 187
}  // namespace internal
}  // namespace v8

#endif  // V8_CANCELABLE_TASK_H_