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.
5 #ifndef CONTENT_RENDERER_SCHEDULER_TASK_QUEUE_MANAGER_H_
6 #define CONTENT_RENDERER_SCHEDULER_TASK_QUEUE_MANAGER_H_
10 #include "base/atomic_sequence_num.h"
11 #include "base/debug/task_annotator.h"
12 #include "base/macros.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/pending_task.h"
16 #include "base/synchronization/lock.h"
17 #include "base/threading/thread_checker.h"
18 #include "components/scheduler/child/task_queue_impl.h"
19 #include "components/scheduler/child/task_queue_selector.h"
20 #include "components/scheduler/scheduler_export.h"
25 namespace trace_event
{
26 class ConvertableToTraceFormat
;
28 } // namespace trace_event
35 } // namespace internal
37 class NestableSingleThreadTaskRunner
;
39 // The task queue manager provides N task queues and a selector interface for
40 // choosing which task queue to service next. Each task queue consists of two
43 // 1. Incoming task queue. Tasks that are posted get immediately appended here.
44 // When a task is appended into an empty incoming queue, the task manager
45 // work function (DoWork) is scheduled to run on the main task runner.
47 // 2. Work queue. If a work queue is empty when DoWork() is entered, tasks from
48 // the incoming task queue (if any) are moved here. The work queues are
49 // registered with the selector as input to the scheduling decision.
51 class SCHEDULER_EXPORT TaskQueueManager
52 : public internal::TaskQueueSelector::Observer
{
54 // Create a task queue manager where |main_task_runner| identifies the thread
55 // on which where the tasks are eventually run. Category strings must have
56 // application lifetime (statics or literals). They may not include " chars.
58 scoped_refptr
<NestableSingleThreadTaskRunner
> main_task_runner
,
59 const char* disabled_by_default_tracing_category
,
60 const char* disabled_by_default_verbose_tracing_category
);
61 ~TaskQueueManager() override
;
63 // Returns the time of the next pending delayed task in any queue. Ignores
64 // any delayed tasks whose delay has expired. Returns a null TimeTicks object
65 // if no tasks are pending. NOTE this is somewhat expensive since every queue
67 base::TimeTicks
NextPendingDelayedTaskRunTime();
69 // Set the number of tasks executed in a single invocation of the task queue
70 // manager. Increasing the batch size can reduce the overhead of yielding
71 // back to the main message loop -- at the cost of potentially delaying other
72 // tasks posted to the main loop. The batch size is 1 by default.
73 void SetWorkBatchSize(int work_batch_size
);
75 // These functions can only be called on the same thread that the task queue
76 // manager executes its tasks on.
77 void AddTaskObserver(base::MessageLoop::TaskObserver
* task_observer
);
78 void RemoveTaskObserver(base::MessageLoop::TaskObserver
* task_observer
);
80 void SetTimeSourceForTesting(scoped_ptr
<base::TickClock
> time_source
);
82 // Returns true if any task from a monitored task queue was was run since the
83 // last call to GetAndClearSystemIsQuiescentBit.
84 bool GetAndClearSystemIsQuiescentBit();
86 // Creates a task queue with the given |spec|. Must be called on the thread
87 // this class was created on.
88 scoped_refptr
<internal::TaskQueueImpl
> NewTaskQueue(
89 const TaskQueue::Spec
& spec
);
92 friend class internal::LazyNow
;
93 friend class internal::TaskQueueImpl
;
94 friend class TaskQueueManagerTest
;
96 class DeletionSentinel
: public base::RefCounted
<DeletionSentinel
> {
98 friend class base::RefCounted
<DeletionSentinel
>;
99 ~DeletionSentinel() {}
102 // Unregisters a TaskQueue previously created by |NewTaskQueue()|.
103 // NOTE we have to flush the queue from |newly_updatable_| which means as a
104 // side effect MoveNewlyUpdatableQueuesIntoUpdatableQueueSet is called by this
106 void UnregisterTaskQueue(scoped_refptr
<internal::TaskQueueImpl
> task_queue
);
108 // TaskQueueSelector::Observer implementation:
109 void OnTaskQueueEnabled(internal::TaskQueueImpl
* queue
) override
;
111 // Called by the task queue to register a new pending task.
112 void DidQueueTask(const internal::TaskQueueImpl::Task
& pending_task
);
114 // Post a task to call DoWork() on the main task runner. Only one pending
115 // DoWork is allowed from the main thread, to prevent an explosion of pending
117 void MaybePostDoWorkOnMainRunner();
119 // Use the selector to choose a pending task and run it.
120 void DoWork(bool decrement_pending_dowork_count
);
122 // Delayed Tasks with run_times <= Now() are enqueued onto the work queue.
123 // Reloads any empty work queues which have automatic pumping enabled and
124 // which are eligible to be auto pumped based on the |previous_task| which was
125 // run and |should_trigger_wakeup|. Call with an empty |previous_task| if no
126 // task was just run.
127 void UpdateWorkQueues(bool should_trigger_wakeup
,
128 const internal::TaskQueueImpl::Task
* previous_task
);
130 // Chooses the next work queue to service. Returns true if |out_queue|
131 // indicates the queue from which the next task should be run, false to
132 // avoid running any tasks.
133 bool SelectQueueToService(internal::TaskQueueImpl
** out_queue
);
135 // Runs a single nestable task from the |queue|. On exit, |out_task| will
136 // contain the task which was executed. Non-nestable task are reposted on the
137 // run loop. The queue must not be empty.
138 enum class ProcessTaskResult
{
141 TASK_QUEUE_MANAGER_DELETED
143 ProcessTaskResult
ProcessTaskFromWorkQueue(
144 internal::TaskQueueImpl
* queue
,
145 internal::TaskQueueImpl::Task
* out_previous_task
);
147 bool RunsTasksOnCurrentThread() const;
148 bool PostDelayedTask(const tracked_objects::Location
& from_here
,
149 const base::Closure
& task
,
150 base::TimeDelta delay
);
151 bool PostNonNestableDelayedTask(const tracked_objects::Location
& from_here
,
152 const base::Closure
& task
,
153 base::TimeDelta delay
);
155 base::TimeTicks
Now() const;
157 int GetNextSequenceNumber();
159 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>
160 AsValueWithSelectorResult(bool should_run
,
161 internal::TaskQueueImpl
* selected_queue
) const;
163 // Causes DoWork to start calling UpdateWorkQueue for |queue|. Can be called
165 void RegisterAsUpdatableTaskQueue(internal::TaskQueueImpl
* queue
);
167 // Prevents DoWork from calling UpdateWorkQueue for |queue|. Must be called
168 // from the thread the TaskQueueManager was created on.
169 void UnregisterAsUpdatableTaskQueue(internal::TaskQueueImpl
* queue
);
171 // Schedule a call to DelayedDoWork at |delayed_run_time| which will call
172 // TaskQueueImpl::MoveReadyDelayedTasksToIncomingQueue for |queue|.
173 // Can be called from any thread.
174 void ScheduleDelayedWork(internal::TaskQueueImpl
* queue
,
175 base::TimeTicks delayed_run_time
,
176 internal::LazyNow
* lazy_now
);
178 // Function calling ScheduleDelayedWork that's suitable for use in base::Bind.
179 void ScheduleDelayedWorkTask(scoped_refptr
<internal::TaskQueueImpl
> queue
,
180 base::TimeTicks delayed_run_time
);
182 // Calls WakeupReadyDelayedQueues followed by DoWork so that ready delayed
183 // tasks are enqueued and run. Must be called from the main thread.
184 void DelayedDoWork();
186 // Call TaskQueueImpl::MoveReadyDelayedTasksToIncomingQueue for each
187 // registered queue for which the delay has elapsed.
188 void WakeupReadyDelayedQueues(internal::LazyNow
* lazy_now
);
190 void MoveNewlyUpdatableQueuesIntoUpdatableQueueSet();
192 std::set
<scoped_refptr
<internal::TaskQueueImpl
>> queues_
;
194 // We have to be careful when deleting a queue because some of the code uses
195 // raw pointers and doesn't expect the rug to be pulled out from underneath.
196 std::set
<scoped_refptr
<internal::TaskQueueImpl
>> queues_to_delete_
;
198 // This lock guards only |newly_updatable_|. It's not expected to be heavily
200 base::Lock newly_updatable_lock_
;
201 std::vector
<internal::TaskQueueImpl
*> newly_updatable_
;
203 // Set of task queues with avaliable work on the incoming queue. This should
204 // only be accessed from the main thread.
205 std::set
<internal::TaskQueueImpl
*> updatable_queue_set_
;
207 typedef std::multimap
<base::TimeTicks
, internal::TaskQueueImpl
*>
208 DelayedWakeupMultimap
;
210 DelayedWakeupMultimap delayed_wakeup_map_
;
212 base::AtomicSequenceNumber task_sequence_num_
;
213 base::debug::TaskAnnotator task_annotator_
;
215 base::ThreadChecker main_thread_checker_
;
216 scoped_refptr
<NestableSingleThreadTaskRunner
> main_task_runner_
;
217 internal::TaskQueueSelector selector_
;
219 base::Closure do_work_from_main_thread_closure_
;
220 base::Closure do_work_from_other_thread_closure_
;
221 base::Closure delayed_queue_wakeup_closure_
;
223 bool task_was_run_on_quiescence_monitored_queue_
;
225 // The pending_dowork_count_ is only tracked on the main thread since that's
226 // where re-entrant problems happen.
227 int pending_dowork_count_
;
229 int work_batch_size_
;
231 scoped_ptr
<base::TickClock
> time_source_
;
233 base::ObserverList
<base::MessageLoop::TaskObserver
> task_observers_
;
235 const char* disabled_by_default_tracing_category_
;
236 const char* disabled_by_default_verbose_tracing_category_
;
238 scoped_refptr
<DeletionSentinel
> deletion_sentinel_
;
239 base::WeakPtrFactory
<TaskQueueManager
> weak_factory_
;
241 DISALLOW_COPY_AND_ASSIGN(TaskQueueManager
);
244 } // namespace scheduler
246 #endif // CONTENT_RENDERER_SCHEDULER_TASK_QUEUE_MANAGER_H_