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.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 // TaskQueueSelector::Observer implementation:
103 void OnTaskQueueEnabled() override
;
105 // Called by the task queue to register a new pending task.
106 void DidQueueTask(const base::PendingTask
& pending_task
);
108 // Post a task to call DoWork() on the main task runner. Only one pending
109 // DoWork is allowed from the main thread, to prevent an explosion of pending
111 void MaybePostDoWorkOnMainRunner();
113 // Use the selector to choose a pending task and run it.
114 void DoWork(bool posted_from_main_thread
);
116 // Delayed Tasks with run_times <= Now() are enqueued onto the work queue.
117 // Reloads any empty work queues which have automatic pumping enabled and
118 // which are eligible to be auto pumped based on the |previous_task| which was
119 // run and |should_trigger_wakeup|. Call with an empty |previous_task| if no
120 // task was just run.
121 void UpdateWorkQueues(bool should_trigger_wakeup
,
122 const base::PendingTask
* previous_task
);
124 // Chooses the next work queue to service. Returns true if |out_queue|
125 // indicates the queue from which the next task should be run, false to
126 // avoid running any tasks.
127 bool SelectQueueToService(internal::TaskQueueImpl
** out_queue
);
129 // Runs a single nestable task from the |queue|. On exit, |out_task| will
130 // contain the task which was executed. Non-nestable task are reposted on the
131 // run loop. The queue must not be empty. Returns true if the TaskQueueManager
132 // got deleted, and false otherwise.
133 bool ProcessTaskFromWorkQueue(internal::TaskQueueImpl
* queue
,
134 base::PendingTask
* out_previous_task
);
136 bool RunsTasksOnCurrentThread() const;
137 bool PostDelayedTask(const tracked_objects::Location
& from_here
,
138 const base::Closure
& task
,
139 base::TimeDelta delay
);
140 bool PostNonNestableDelayedTask(const tracked_objects::Location
& from_here
,
141 const base::Closure
& task
,
142 base::TimeDelta delay
);
144 base::TimeTicks
Now() const;
146 int GetNextSequenceNumber();
148 scoped_refptr
<base::trace_event::ConvertableToTraceFormat
>
149 AsValueWithSelectorResult(bool should_run
,
150 internal::TaskQueueImpl
* selected_queue
) const;
152 // Causes DoWork to start calling UpdateWorkQueue for |queue|. Can be called
154 void RegisterAsUpdatableTaskQueue(internal::TaskQueueImpl
* queue
);
156 // Prevents DoWork from calling UpdateWorkQueue for |queue|. Must be called
157 // from the thread the TaskQueueManager was created on.
158 void UnregisterAsUpdatableTaskQueue(internal::TaskQueueImpl
* queue
);
160 std::set
<scoped_refptr
<internal::TaskQueueImpl
>> queues_
;
162 // This lock guards only |newly_updatable_|. It's not expected to be heavily
164 base::Lock newly_updatable_lock_
;
165 std::vector
<internal::TaskQueueImpl
*> newly_updatable_
;
167 // Set of task queues with avaliable work on the incoming queue. This should
168 // only be accessed from the main thread.
169 std::set
<internal::TaskQueueImpl
*> updatable_queue_set_
;
171 base::AtomicSequenceNumber task_sequence_num_
;
172 base::debug::TaskAnnotator task_annotator_
;
174 base::ThreadChecker main_thread_checker_
;
175 scoped_refptr
<NestableSingleThreadTaskRunner
> main_task_runner_
;
176 internal::TaskQueueSelector selector_
;
178 base::Closure do_work_from_main_thread_closure_
;
179 base::Closure do_work_from_other_thread_closure_
;
181 bool task_was_run_on_quiescence_monitored_queue_
;
183 // The pending_dowork_count_ is only tracked on the main thread since that's
184 // where re-entrant problems happen.
185 int pending_dowork_count_
;
187 int work_batch_size_
;
189 scoped_ptr
<base::TickClock
> time_source_
;
191 base::ObserverList
<base::MessageLoop::TaskObserver
> task_observers_
;
193 const char* disabled_by_default_tracing_category_
;
194 const char* disabled_by_default_verbose_tracing_category_
;
196 scoped_refptr
<DeletionSentinel
> deletion_sentinel_
;
197 base::WeakPtrFactory
<TaskQueueManager
> weak_factory_
;
199 DISALLOW_COPY_AND_ASSIGN(TaskQueueManager
);
202 } // namespace scheduler
204 #endif // CONTENT_RENDERER_SCHEDULER_TASK_QUEUE_MANAGER_H_