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