1 // Copyright 2013 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/message_loop/incoming_task_queue.h"
6
7 #include <limits>
8 #include <utility>
9
10 #include "base/location.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/synchronization/waitable_event.h"
13 #include "base/time/time.h"
14 #include "build/build_config.h"
15
16 namespace base {
17 namespace internal {
18
19 namespace {
20
21 #if DCHECK_IS_ON()
22 // Delays larger than this are often bogus, and a warning should be emitted in
23 // debug builds to warn developers. http://crbug.com/450045
24 const int kTaskDelayWarningThresholdInSeconds =
25 14 * 24 * 60 * 60; // 14 days.
26 #endif
27
28 // Returns true if MessagePump::ScheduleWork() must be called one
29 // time for every task that is added to the MessageLoop incoming queue.
AlwaysNotifyPump(MessageLoop::Type type)30 bool AlwaysNotifyPump(MessageLoop::Type type) {
31 #if defined(OS_ANDROID)
32 // The Android UI message loop needs to get notified each time a task is
33 // added
34 // to the incoming queue.
35 return type == MessageLoop::TYPE_UI || type == MessageLoop::TYPE_JAVA;
36 #else
37 return false;
38 #endif
39 }
40
CalculateDelayedRuntime(TimeDelta delay)41 TimeTicks CalculateDelayedRuntime(TimeDelta delay) {
42 TimeTicks delayed_run_time;
43 if (delay > TimeDelta())
44 delayed_run_time = TimeTicks::Now() + delay;
45 else
46 DCHECK_EQ(delay.InMilliseconds(), 0) << "delay should not be negative";
47 return delayed_run_time;
48 }
49
50 } // namespace
51
IncomingTaskQueue(MessageLoop * message_loop)52 IncomingTaskQueue::IncomingTaskQueue(MessageLoop* message_loop)
53 : high_res_task_count_(0),
54 message_loop_(message_loop),
55 next_sequence_num_(0),
56 message_loop_scheduled_(false),
57 always_schedule_work_(AlwaysNotifyPump(message_loop_->type())),
58 is_ready_for_scheduling_(false) {
59 }
60
AddToIncomingQueue(const tracked_objects::Location & from_here,OnceClosure task,TimeDelta delay,bool nestable)61 bool IncomingTaskQueue::AddToIncomingQueue(
62 const tracked_objects::Location& from_here,
63 OnceClosure task,
64 TimeDelta delay,
65 bool nestable) {
66 DCHECK(task);
67 DLOG_IF(WARNING,
68 delay.InSeconds() > kTaskDelayWarningThresholdInSeconds)
69 << "Requesting super-long task delay period of " << delay.InSeconds()
70 << " seconds from here: " << from_here.ToString();
71
72 PendingTask pending_task(from_here, std::move(task),
73 CalculateDelayedRuntime(delay), nestable);
74 #if defined(OS_WIN)
75 // We consider the task needs a high resolution timer if the delay is
76 // more than 0 and less than 32ms. This caps the relative error to
77 // less than 50% : a 33ms wait can wake at 48ms since the default
78 // resolution on Windows is between 10 and 15ms.
79 if (delay > TimeDelta() &&
80 delay.InMilliseconds() < (2 * Time::kMinLowResolutionThresholdMs)) {
81 pending_task.is_high_res = true;
82 }
83 #endif
84 return PostPendingTask(&pending_task);
85 }
86
HasHighResolutionTasks()87 bool IncomingTaskQueue::HasHighResolutionTasks() {
88 AutoLock lock(incoming_queue_lock_);
89 return high_res_task_count_ > 0;
90 }
91
IsIdleForTesting()92 bool IncomingTaskQueue::IsIdleForTesting() {
93 AutoLock lock(incoming_queue_lock_);
94 return incoming_queue_.empty();
95 }
96
ReloadWorkQueue(TaskQueue * work_queue)97 int IncomingTaskQueue::ReloadWorkQueue(TaskQueue* work_queue) {
98 // Make sure no tasks are lost.
99 DCHECK(work_queue->empty());
100
101 // Acquire all we can from the inter-thread queue with one lock acquisition.
102 AutoLock lock(incoming_queue_lock_);
103 if (incoming_queue_.empty()) {
104 // If the loop attempts to reload but there are no tasks in the incoming
105 // queue, that means it will go to sleep waiting for more work. If the
106 // incoming queue becomes nonempty we need to schedule it again.
107 message_loop_scheduled_ = false;
108 } else {
109 incoming_queue_.swap(*work_queue);
110 }
111 // Reset the count of high resolution tasks since our queue is now empty.
112 int high_res_tasks = high_res_task_count_;
113 high_res_task_count_ = 0;
114 return high_res_tasks;
115 }
116
WillDestroyCurrentMessageLoop()117 void IncomingTaskQueue::WillDestroyCurrentMessageLoop() {
118 base::subtle::AutoWriteLock lock(message_loop_lock_);
119 message_loop_ = NULL;
120 }
121
StartScheduling()122 void IncomingTaskQueue::StartScheduling() {
123 bool schedule_work;
124 {
125 AutoLock lock(incoming_queue_lock_);
126 DCHECK(!is_ready_for_scheduling_);
127 DCHECK(!message_loop_scheduled_);
128 is_ready_for_scheduling_ = true;
129 schedule_work = !incoming_queue_.empty();
130 }
131 if (schedule_work) {
132 DCHECK(message_loop_);
133 // Don't need to lock |message_loop_lock_| here because this function is
134 // called by MessageLoop on its thread.
135 message_loop_->ScheduleWork();
136 }
137 }
138
~IncomingTaskQueue()139 IncomingTaskQueue::~IncomingTaskQueue() {
140 // Verify that WillDestroyCurrentMessageLoop() has been called.
141 DCHECK(!message_loop_);
142 }
143
PostPendingTask(PendingTask * pending_task)144 bool IncomingTaskQueue::PostPendingTask(PendingTask* pending_task) {
145 // Warning: Don't try to short-circuit, and handle this thread's tasks more
146 // directly, as it could starve handling of foreign threads. Put every task
147 // into this queue.
148
149 // Ensures |message_loop_| isn't destroyed while running.
150 base::subtle::AutoReadLock hold_message_loop(message_loop_lock_);
151
152 if (!message_loop_) {
153 pending_task->task.Reset();
154 return false;
155 }
156
157 bool schedule_work = false;
158 {
159 AutoLock hold(incoming_queue_lock_);
160
161 #if defined(OS_WIN)
162 if (pending_task->is_high_res)
163 ++high_res_task_count_;
164 #endif
165
166 // Initialize the sequence number. The sequence number is used for delayed
167 // tasks (to facilitate FIFO sorting when two tasks have the same
168 // delayed_run_time value) and for identifying the task in about:tracing.
169 pending_task->sequence_num = next_sequence_num_++;
170
171 message_loop_->task_annotator()->DidQueueTask("MessageLoop::PostTask",
172 *pending_task);
173
174 bool was_empty = incoming_queue_.empty();
175 incoming_queue_.push(std::move(*pending_task));
176
177 if (is_ready_for_scheduling_ &&
178 (always_schedule_work_ || (!message_loop_scheduled_ && was_empty))) {
179 schedule_work = true;
180 // After we've scheduled the message loop, we do not need to do so again
181 // until we know it has processed all of the work in our queue and is
182 // waiting for more work again. The message loop will always attempt to
183 // reload from the incoming queue before waiting again so we clear this
184 // flag in ReloadWorkQueue().
185 message_loop_scheduled_ = true;
186 }
187 }
188
189 // Wake up the message loop and schedule work. This is done outside
190 // |incoming_queue_lock_| because signaling the message loop may cause this
191 // thread to be switched. If |incoming_queue_lock_| is held, any other thread
192 // that wants to post a task will be blocked until this thread switches back
193 // in and releases |incoming_queue_lock_|.
194 if (schedule_work)
195 message_loop_->ScheduleWork();
196
197 return true;
198 }
199
200 } // namespace internal
201 } // namespace base
202