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_
8 #include "base/atomic_sequence_num.h"
9 #include "base/debug/task_annotator.h"
10 #include "base/macros.h"
11 #include "base/memory/weak_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/pending_task.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/synchronization/lock.h"
16 #include "base/threading/thread_checker.h"
17 #include "content/child/scheduler/task_queue_selector.h"
18 #include "content/common/content_export.h"
21 namespace trace_event
{
22 class ConvertableToTraceFormat
;
36 class TaskQueueSelector
;
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 CONTENT_EXPORT TaskQueueManager
52 : public TaskQueueSelector::Observer
{
54 // Keep TaskQueue::PumpPolicyToString in sync with this enum.
55 enum class PumpPolicy
{
56 // Tasks posted to an incoming queue with an AUTO pump policy will be
57 // automatically scheduled for execution or transferred to the work queue
60 // Tasks posted to an incoming queue with an AFTER_WAKEUP pump policy
61 // will be scheduled for execution or transferred to the work queue
62 // automatically but only after another queue has executed a task.
64 // Tasks posted to an incoming queue with a MANUAL will not be
65 // automatically scheduled for execution or transferred to the work queue.
66 // Instead, the selector should call PumpQueue() when necessary to bring
67 // in new tasks for execution.
71 // Create a task queue manager with |task_queue_count| task queues.
72 // |main_task_runner| identifies the thread on which where the tasks are
73 // eventually run. |selector| is used to choose which task queue to service.
74 // It should outlive this class. Category strings must have application
75 // lifetime (statics or literals). They may not include " chars.
77 size_t task_queue_count
,
78 scoped_refptr
<NestableSingleThreadTaskRunner
> main_task_runner
,
79 TaskQueueSelector
* selector
,
80 const char* disabled_by_default_tracing_category
);
81 ~TaskQueueManager() override
;
83 // Returns the task runner which targets the queue selected by |queue_index|.
84 scoped_refptr
<base::SingleThreadTaskRunner
> TaskRunnerForQueue(
85 size_t queue_index
) const;
87 // Sets the pump policy for the |queue_index| to |pump_policy|. By
88 // default queues are created with AUTO_PUMP_POLICY.
89 void SetPumpPolicy(size_t queue_index
, PumpPolicy pump_policy
);
91 // Reloads new tasks from the incoming queue for |queue_index| into the work
92 // queue, regardless of whether the work queue is empty or not. After this,
93 // this function ensures that the tasks in the work queue, if any, are
94 // scheduled for execution.
96 // This function only needs to be called if automatic pumping is disabled
97 // for |queue_index|. See |SetQueueAutoPumpPolicy|. By default automatic
98 // pumping is enabled for all queues.
99 void PumpQueue(size_t queue_index
);
101 // Returns true if there no tasks in either the work or incoming task queue
102 // identified by |queue_index|. Note that this function involves taking a
103 // lock, so calling it has some overhead.
104 bool IsQueueEmpty(size_t queue_index
) const;
106 // Returns the time of the next pending delayed task in any queue. Ignores
107 // any delayed tasks whose delay has expired. Returns a null TimeTicks object
108 // if no tasks are pending. NOTE this is somewhat expensive since every queue
110 base::TimeTicks
NextPendingDelayedTaskRunTime();
112 // Set the name |queue_index| for tracing purposes. |name| must be a pointer
113 // to a static string.
114 void SetQueueName(size_t queue_index
, const char* name
);
116 // Set the number of tasks executed in a single invocation of the task queue
117 // manager. Increasing the batch size can reduce the overhead of yielding
118 // back to the main message loop -- at the cost of potentially delaying other
119 // tasks posted to the main loop. The batch size is 1 by default.
120 void SetWorkBatchSize(int work_batch_size
);
122 // These functions can only be called on the same thread that the task queue
123 // manager executes its tasks on.
124 void AddTaskObserver(base::MessageLoop::TaskObserver
* task_observer
);
125 void RemoveTaskObserver(base::MessageLoop::TaskObserver
* task_observer
);
127 void SetTimeSourceForTesting(scoped_refptr
<cc::TestNowSource
> time_source
);
129 // Returns a bitmap where a bit is set iff a task on the corresponding queue
130 // was run since the last call to GetAndClearTaskWasRunOnQueueBitmap.
131 uint64
GetAndClearTaskWasRunOnQueueBitmap();
134 // TaskQueueSelector::Observer implementation:
135 void OnTaskQueueEnabled() override
;
137 friend class internal::LazyNow
;
138 friend class internal::TaskQueue
;
140 class DeletionSentinel
: public base::RefCounted
<DeletionSentinel
> {
142 friend class base::RefCounted
<DeletionSentinel
>;
143 ~DeletionSentinel() {}
146 // Called by the task queue to register a new pending task and allocate a
147 // sequence number for it.
148 void DidQueueTask(base::PendingTask
* pending_task
);
150 // Post a task to call DoWork() on the main task runner. Only one pending
151 // DoWork is allowed from the main thread, to prevent an explosion of pending
153 void MaybePostDoWorkOnMainRunner();
155 // Use the selector to choose a pending task and run it.
156 void DoWork(bool posted_from_main_thread
);
158 // Delayed Tasks with run_times <= Now() are enqueued onto the work queue.
159 // Reloads any empty work queues which have automatic pumping enabled and
160 // which are eligible to be auto pumped based on the |previous_task| which was
161 // run. Call with an empty |previous_task| if no task was just run. Returns
162 // true if any work queue has tasks after doing this.
163 // |next_pending_delayed_task| should be the time of the next known delayed
164 // task. It is updated if any task is found which should run earlier.
165 bool UpdateWorkQueues(const base::PendingTask
* previous_task
);
167 // Chooses the next work queue to service. Returns true if |out_queue_index|
168 // indicates the queue from which the next task should be run, false to
169 // avoid running any tasks.
170 bool SelectWorkQueueToService(size_t* out_queue_index
);
172 // Runs a single nestable task from the work queue designated by
173 // |queue_index|. If |has_previous_task| is true, |previous_task| should
174 // contain the previous task in this work batch. Non-nestable task are
175 // reposted on the run loop. The queue must not be empty.
176 // Returns true if the TaskQueueManager got deleted, and false otherwise.
177 bool ProcessTaskFromWorkQueue(size_t queue_index
,
178 bool has_previous_task
,
179 base::PendingTask
* previous_task
);
181 bool RunsTasksOnCurrentThread() const;
182 bool PostDelayedTask(const tracked_objects::Location
& from_here
,
183 const base::Closure
& task
,
184 base::TimeDelta delay
);
185 bool PostNonNestableDelayedTask(const tracked_objects::Location
& from_here
,
186 const base::Closure
& task
,
187 base::TimeDelta delay
);
188 internal::TaskQueue
* Queue(size_t queue_index
) const;
190 base::TimeTicks
Now() const;
192 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>
193 AsValueWithSelectorResult(bool should_run
, size_t selected_queue
) const;
195 std::vector
<scoped_refptr
<internal::TaskQueue
>> queues_
;
196 base::AtomicSequenceNumber task_sequence_num_
;
197 base::debug::TaskAnnotator task_annotator_
;
199 base::ThreadChecker main_thread_checker_
;
200 scoped_refptr
<NestableSingleThreadTaskRunner
> main_task_runner_
;
201 TaskQueueSelector
* selector_
;
203 base::Closure do_work_from_main_thread_closure_
;
204 base::Closure do_work_from_other_thread_closure_
;
206 uint64 task_was_run_bitmap_
;
208 // The pending_dowork_count_ is only tracked on the main thread since that's
209 // where re-entrant problems happen.
210 int pending_dowork_count_
;
212 int work_batch_size_
;
214 scoped_refptr
<cc::TestNowSource
> time_source_
;
216 ObserverList
<base::MessageLoop::TaskObserver
> task_observers_
;
218 const char* disabled_by_default_tracing_category_
;
220 scoped_refptr
<DeletionSentinel
> deletion_sentinel_
;
221 base::WeakPtrFactory
<TaskQueueManager
> weak_factory_
;
223 DISALLOW_COPY_AND_ASSIGN(TaskQueueManager
);
226 } // namespace content
228 #endif // CONTENT_RENDERER_SCHEDULER_TASK_QUEUE_MANAGER_H_