1 // Copyright 2014 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 #include "base/task/cancelable_task_tracker.h"
6
7 #include <stddef.h>
8
9 #include <utility>
10
11 #include "base/bind.h"
12 #include "base/callback_helpers.h"
13 #include "base/compiler_specific.h"
14 #include "base/location.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/synchronization/cancellation_flag.h"
18 #include "base/task_runner.h"
19 #include "base/thread_task_runner_handle.h"
20
21 using base::Bind;
22 using base::CancellationFlag;
23 using base::Closure;
24 using base::hash_map;
25 using base::TaskRunner;
26
27 namespace {
28
RunIfNotCanceled(const CancellationFlag * flag,const Closure & task)29 void RunIfNotCanceled(const CancellationFlag* flag, const Closure& task) {
30 if (!flag->IsSet())
31 task.Run();
32 }
33
RunIfNotCanceledThenUntrack(const CancellationFlag * flag,const Closure & task,const Closure & untrack)34 void RunIfNotCanceledThenUntrack(const CancellationFlag* flag,
35 const Closure& task,
36 const Closure& untrack) {
37 RunIfNotCanceled(flag, task);
38 untrack.Run();
39 }
40
IsCanceled(const CancellationFlag * flag,base::ScopedClosureRunner *)41 bool IsCanceled(const CancellationFlag* flag,
42 base::ScopedClosureRunner* /* cleanup_runner */) {
43 return flag->IsSet();
44 }
45
RunAndDeleteFlag(const Closure & closure,const CancellationFlag * flag)46 void RunAndDeleteFlag(const Closure& closure, const CancellationFlag* flag) {
47 closure.Run();
48 delete flag;
49 }
50
RunOrPostToTaskRunner(TaskRunner * task_runner,const Closure & closure)51 void RunOrPostToTaskRunner(TaskRunner* task_runner, const Closure& closure) {
52 if (task_runner->RunsTasksOnCurrentThread())
53 closure.Run();
54 else
55 task_runner->PostTask(FROM_HERE, closure);
56 }
57
58 } // namespace
59
60 namespace base {
61
62 // static
63 const CancelableTaskTracker::TaskId CancelableTaskTracker::kBadTaskId = 0;
64
CancelableTaskTracker()65 CancelableTaskTracker::CancelableTaskTracker()
66 : next_id_(1),weak_factory_(this) {}
67
~CancelableTaskTracker()68 CancelableTaskTracker::~CancelableTaskTracker() {
69 DCHECK(thread_checker_.CalledOnValidThread());
70
71 TryCancelAll();
72 }
73
PostTask(TaskRunner * task_runner,const tracked_objects::Location & from_here,const Closure & task)74 CancelableTaskTracker::TaskId CancelableTaskTracker::PostTask(
75 TaskRunner* task_runner,
76 const tracked_objects::Location& from_here,
77 const Closure& task) {
78 DCHECK(thread_checker_.CalledOnValidThread());
79
80 return PostTaskAndReply(task_runner, from_here, task, Bind(&base::DoNothing));
81 }
82
PostTaskAndReply(TaskRunner * task_runner,const tracked_objects::Location & from_here,const Closure & task,const Closure & reply)83 CancelableTaskTracker::TaskId CancelableTaskTracker::PostTaskAndReply(
84 TaskRunner* task_runner,
85 const tracked_objects::Location& from_here,
86 const Closure& task,
87 const Closure& reply) {
88 DCHECK(thread_checker_.CalledOnValidThread());
89
90 // We need a MessageLoop to run reply.
91 DCHECK(base::ThreadTaskRunnerHandle::IsSet());
92
93 // Owned by reply callback below.
94 CancellationFlag* flag = new CancellationFlag();
95
96 TaskId id = next_id_;
97 next_id_++; // int64_t is big enough that we ignore the potential overflow.
98
99 const Closure& untrack_closure =
100 Bind(&CancelableTaskTracker::Untrack, weak_factory_.GetWeakPtr(), id);
101 bool success =
102 task_runner->PostTaskAndReply(from_here,
103 Bind(&RunIfNotCanceled, flag, task),
104 Bind(&RunIfNotCanceledThenUntrack,
105 base::Owned(flag),
106 reply,
107 untrack_closure));
108
109 if (!success)
110 return kBadTaskId;
111
112 Track(id, flag);
113 return id;
114 }
115
NewTrackedTaskId(IsCanceledCallback * is_canceled_cb)116 CancelableTaskTracker::TaskId CancelableTaskTracker::NewTrackedTaskId(
117 IsCanceledCallback* is_canceled_cb) {
118 DCHECK(thread_checker_.CalledOnValidThread());
119 DCHECK(base::ThreadTaskRunnerHandle::IsSet());
120
121 TaskId id = next_id_;
122 next_id_++; // int64_t is big enough that we ignore the potential overflow.
123
124 // Will be deleted by |untrack_and_delete_flag| after Untrack().
125 CancellationFlag* flag = new CancellationFlag();
126
127 Closure untrack_and_delete_flag = Bind(
128 &RunAndDeleteFlag,
129 Bind(&CancelableTaskTracker::Untrack, weak_factory_.GetWeakPtr(), id),
130 flag);
131
132 // Will always run |untrack_and_delete_flag| on current MessageLoop.
133 base::ScopedClosureRunner* untrack_and_delete_flag_runner =
134 new base::ScopedClosureRunner(Bind(&RunOrPostToTaskRunner,
135 base::ThreadTaskRunnerHandle::Get(),
136 untrack_and_delete_flag));
137
138 *is_canceled_cb =
139 Bind(&IsCanceled, flag, base::Owned(untrack_and_delete_flag_runner));
140
141 Track(id, flag);
142 return id;
143 }
144
TryCancel(TaskId id)145 void CancelableTaskTracker::TryCancel(TaskId id) {
146 DCHECK(thread_checker_.CalledOnValidThread());
147
148 hash_map<TaskId, CancellationFlag*>::const_iterator it = task_flags_.find(id);
149 if (it == task_flags_.end()) {
150 // Two possibilities:
151 //
152 // 1. The task has already been untracked.
153 // 2. The TaskId is bad or unknown.
154 //
155 // Since this function is best-effort, it's OK to ignore these.
156 return;
157 }
158 it->second->Set();
159 }
160
TryCancelAll()161 void CancelableTaskTracker::TryCancelAll() {
162 DCHECK(thread_checker_.CalledOnValidThread());
163
164 for (hash_map<TaskId, CancellationFlag*>::const_iterator it =
165 task_flags_.begin();
166 it != task_flags_.end();
167 ++it) {
168 it->second->Set();
169 }
170 }
171
HasTrackedTasks() const172 bool CancelableTaskTracker::HasTrackedTasks() const {
173 DCHECK(thread_checker_.CalledOnValidThread());
174 return !task_flags_.empty();
175 }
176
Track(TaskId id,CancellationFlag * flag)177 void CancelableTaskTracker::Track(TaskId id, CancellationFlag* flag) {
178 DCHECK(thread_checker_.CalledOnValidThread());
179
180 bool success = task_flags_.insert(std::make_pair(id, flag)).second;
181 DCHECK(success);
182 }
183
Untrack(TaskId id)184 void CancelableTaskTracker::Untrack(TaskId id) {
185 DCHECK(thread_checker_.CalledOnValidThread());
186 size_t num = task_flags_.erase(id);
187 DCHECK_EQ(1u, num);
188 }
189
190 } // namespace base
191