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 
9 #include "base/location.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/metrics/histogram.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 #ifndef NDEBUG
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.
30 #if defined(OS_ANDROID)
AlwaysNotifyPump(MessageLoop::Type type)31 bool AlwaysNotifyPump(MessageLoop::Type type) {
32   // The Android UI message loop needs to get notified each time a task is
33   // added to the incoming queue.
34   return type == MessageLoop::TYPE_UI || type == MessageLoop::TYPE_JAVA;
35 }
36 #else
AlwaysNotifyPump(MessageLoop::Type)37 bool AlwaysNotifyPump(MessageLoop::Type /* type */) {
38   return false;
39 }
40 #endif
41 
42 }  // namespace
43 
IncomingTaskQueue(MessageLoop * message_loop)44 IncomingTaskQueue::IncomingTaskQueue(MessageLoop* message_loop)
45     : high_res_task_count_(0),
46       message_loop_(message_loop),
47       next_sequence_num_(0),
48       message_loop_scheduled_(false),
49       always_schedule_work_(AlwaysNotifyPump(message_loop_->type())),
50       is_ready_for_scheduling_(false) {
51 }
52 
AddToIncomingQueue(const tracked_objects::Location & from_here,const Closure & task,TimeDelta delay,bool nestable)53 bool IncomingTaskQueue::AddToIncomingQueue(
54     const tracked_objects::Location& from_here,
55     const Closure& task,
56     TimeDelta delay,
57     bool nestable) {
58   DLOG_IF(WARNING,
59           delay.InSeconds() > kTaskDelayWarningThresholdInSeconds)
60       << "Requesting super-long task delay period of " << delay.InSeconds()
61       << " seconds from here: " << from_here.ToString();
62 
63   AutoLock locked(incoming_queue_lock_);
64   PendingTask pending_task(
65       from_here, task, CalculateDelayedRuntime(delay), nestable);
66 #if defined(OS_WIN)
67   // We consider the task needs a high resolution timer if the delay is
68   // more than 0 and less than 32ms. This caps the relative error to
69   // less than 50% : a 33ms wait can wake at 48ms since the default
70   // resolution on Windows is between 10 and 15ms.
71   if (delay > TimeDelta() &&
72       delay.InMilliseconds() < (2 * Time::kMinLowResolutionThresholdMs)) {
73     ++high_res_task_count_;
74     pending_task.is_high_res = true;
75   }
76 #endif
77   return PostPendingTask(&pending_task);
78 }
79 
HasHighResolutionTasks()80 bool IncomingTaskQueue::HasHighResolutionTasks() {
81   AutoLock lock(incoming_queue_lock_);
82   return high_res_task_count_ > 0;
83 }
84 
IsIdleForTesting()85 bool IncomingTaskQueue::IsIdleForTesting() {
86   AutoLock lock(incoming_queue_lock_);
87   return incoming_queue_.empty();
88 }
89 
ReloadWorkQueue(TaskQueue * work_queue)90 int IncomingTaskQueue::ReloadWorkQueue(TaskQueue* work_queue) {
91   // Make sure no tasks are lost.
92   DCHECK(work_queue->empty());
93 
94   // Acquire all we can from the inter-thread queue with one lock acquisition.
95   AutoLock lock(incoming_queue_lock_);
96   if (incoming_queue_.empty()) {
97     // If the loop attempts to reload but there are no tasks in the incoming
98     // queue, that means it will go to sleep waiting for more work. If the
99     // incoming queue becomes nonempty we need to schedule it again.
100     message_loop_scheduled_ = false;
101   } else {
102     incoming_queue_.Swap(work_queue);
103   }
104   // Reset the count of high resolution tasks since our queue is now empty.
105   int high_res_tasks = high_res_task_count_;
106   high_res_task_count_ = 0;
107   return high_res_tasks;
108 }
109 
WillDestroyCurrentMessageLoop()110 void IncomingTaskQueue::WillDestroyCurrentMessageLoop() {
111   AutoLock lock(incoming_queue_lock_);
112   message_loop_ = NULL;
113 }
114 
StartScheduling()115 void IncomingTaskQueue::StartScheduling() {
116   AutoLock lock(incoming_queue_lock_);
117   DCHECK(!is_ready_for_scheduling_);
118   DCHECK(!message_loop_scheduled_);
119   is_ready_for_scheduling_ = true;
120   if (!incoming_queue_.empty())
121     ScheduleWork();
122 }
123 
~IncomingTaskQueue()124 IncomingTaskQueue::~IncomingTaskQueue() {
125   // Verify that WillDestroyCurrentMessageLoop() has been called.
126   DCHECK(!message_loop_);
127 }
128 
CalculateDelayedRuntime(TimeDelta delay)129 TimeTicks IncomingTaskQueue::CalculateDelayedRuntime(TimeDelta delay) {
130   TimeTicks delayed_run_time;
131   if (delay > TimeDelta())
132     delayed_run_time = TimeTicks::Now() + delay;
133   else
134     DCHECK_EQ(delay.InMilliseconds(), 0) << "delay should not be negative";
135   return delayed_run_time;
136 }
137 
PostPendingTask(PendingTask * pending_task)138 bool IncomingTaskQueue::PostPendingTask(PendingTask* pending_task) {
139   // Warning: Don't try to short-circuit, and handle this thread's tasks more
140   // directly, as it could starve handling of foreign threads.  Put every task
141   // into this queue.
142 
143   // This should only be called while the lock is taken.
144   incoming_queue_lock_.AssertAcquired();
145 
146   if (!message_loop_) {
147     pending_task->task.Reset();
148     return false;
149   }
150 
151   // Initialize the sequence number. The sequence number is used for delayed
152   // tasks (to facilitate FIFO sorting when two tasks have the same
153   // delayed_run_time value) and for identifying the task in about:tracing.
154   pending_task->sequence_num = next_sequence_num_++;
155 
156   message_loop_->task_annotator()->DidQueueTask("MessageLoop::PostTask",
157                                                 *pending_task);
158 
159   bool was_empty = incoming_queue_.empty();
160   incoming_queue_.push(*pending_task);
161   pending_task->task.Reset();
162 
163   if (is_ready_for_scheduling_ &&
164       (always_schedule_work_ || (!message_loop_scheduled_ && was_empty))) {
165     ScheduleWork();
166   }
167 
168   return true;
169 }
170 
ScheduleWork()171 void IncomingTaskQueue::ScheduleWork() {
172   DCHECK(is_ready_for_scheduling_);
173   // Wake up the message loop.
174   message_loop_->ScheduleWork();
175   // After we've scheduled the message loop, we do not need to do so again
176   // until we know it has processed all of the work in our queue and is
177   // waiting for more work again. The message loop will always attempt to
178   // reload from the incoming queue before waiting again so we clear this flag
179   // in ReloadWorkQueue().
180   message_loop_scheduled_ = true;
181 }
182 
183 }  // namespace internal
184 }  // namespace base
185