Separate Simple Backend creation from initialization.
[chromium-blink-merge.git] / base / threading / sequenced_worker_pool.h
bloba96cd76d93c19b4b453875bf54923846f50cfafc
1 // Copyright (c) 2012 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 BASE_THREADING_SEQUENCED_WORKER_POOL_H_
6 #define BASE_THREADING_SEQUENCED_WORKER_POOL_H_
8 #include <cstddef>
9 #include <string>
11 #include "base/base_export.h"
12 #include "base/basictypes.h"
13 #include "base/callback_forward.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/task_runner.h"
18 namespace tracked_objects {
19 class Location;
20 } // namespace tracked_objects
22 namespace base {
24 class MessageLoopProxy;
26 template <class T> class DeleteHelper;
28 class SequencedTaskRunner;
30 // A worker thread pool that enforces ordering between sets of tasks. It also
31 // allows you to specify what should happen to your tasks on shutdown.
33 // To enforce ordering, get a unique sequence token from the pool and post all
34 // tasks you want to order with the token. All tasks with the same token are
35 // guaranteed to execute serially, though not necessarily on the same thread.
36 // This means that:
38 // - No two tasks with the same token will run at the same time.
40 // - Given two tasks T1 and T2 with the same token such that T2 will
41 // run after T1, then T2 will start after T1 is destroyed.
43 // - If T2 will run after T1, then all memory changes in T1 and T1's
44 // destruction will be visible to T2.
46 // Example:
47 // SequencedWorkerPool::SequenceToken token = pool.GetSequenceToken();
48 // pool.PostSequencedWorkerTask(token, SequencedWorkerPool::SKIP_ON_SHUTDOWN,
49 // FROM_HERE, base::Bind(...));
50 // pool.PostSequencedWorkerTask(token, SequencedWorkerPool::SKIP_ON_SHUTDOWN,
51 // FROM_HERE, base::Bind(...));
53 // You can make named sequence tokens to make it easier to share a token
54 // across different components.
56 // You can also post tasks to the pool without ordering using PostWorkerTask.
57 // These will be executed in an unspecified order. The order of execution
58 // between tasks with different sequence tokens is also unspecified.
60 // This class is designed to be leaked on shutdown to allow the
61 // CONTINUE_ON_SHUTDOWN behavior to be implemented. To enforce the
62 // BLOCK_SHUTDOWN behavior, you must call Shutdown() which will wait until
63 // the necessary tasks have completed.
65 // Implementation note: This does not use a base::WorkerPool since that does
66 // not enforce shutdown semantics or allow us to specify how many worker
67 // threads to run. For the typical use case of random background work, we don't
68 // necessarily want to be super aggressive about creating threads.
70 // Note that SequencedWorkerPool is RefCountedThreadSafe (inherited
71 // from TaskRunner).
72 class BASE_EXPORT SequencedWorkerPool : public TaskRunner {
73 public:
74 // Defines what should happen to a task posted to the worker pool on
75 // shutdown.
76 enum WorkerShutdown {
77 // Tasks posted with this mode which have not run at shutdown will be
78 // deleted rather than run, and any tasks with this mode running at
79 // shutdown will be ignored (the worker thread will not be joined).
81 // This option provides a nice way to post stuff you don't want blocking
82 // shutdown. For example, you might be doing a slow DNS lookup and if it's
83 // blocked on the OS, you may not want to stop shutdown, since the result
84 // doesn't really matter at that point.
86 // However, you need to be very careful what you do in your callback when
87 // you use this option. Since the thread will continue to run until the OS
88 // terminates the process, the app can be in the process of tearing down
89 // when you're running. This means any singletons or global objects you
90 // use may suddenly become invalid out from under you. For this reason,
91 // it's best to use this only for slow but simple operations like the DNS
92 // example.
93 CONTINUE_ON_SHUTDOWN,
95 // Tasks posted with this mode that have not started executing at
96 // shutdown will be deleted rather than executed. However, any tasks that
97 // have already begun executing when shutdown is called will be allowed
98 // to continue, and will block shutdown until completion.
100 // Note: Because Shutdown() may block while these tasks are executing,
101 // care must be taken to ensure that they do not block on the thread that
102 // called Shutdown(), as this may lead to deadlock.
103 SKIP_ON_SHUTDOWN,
105 // Tasks posted with this mode will block shutdown until they're
106 // executed. Since this can have significant performance implications,
107 // use sparingly.
109 // Generally, this should be used only for user data, for example, a task
110 // writing a preference file.
112 // If a task is posted during shutdown, it will not get run since the
113 // workers may already be stopped. In this case, the post operation will
114 // fail (return false) and the task will be deleted.
115 BLOCK_SHUTDOWN,
118 // Opaque identifier that defines sequencing of tasks posted to the worker
119 // pool.
120 class SequenceToken {
121 public:
122 SequenceToken() : id_(0) {}
123 ~SequenceToken() {}
125 bool Equals(const SequenceToken& other) const {
126 return id_ == other.id_;
129 private:
130 friend class SequencedWorkerPool;
132 explicit SequenceToken(int id) : id_(id) {}
134 int id_;
137 // Allows tests to perform certain actions.
138 class TestingObserver {
139 public:
140 virtual ~TestingObserver() {}
141 virtual void OnHasWork() = 0;
142 virtual void WillWaitForShutdown() = 0;
143 virtual void OnDestruct() = 0;
146 // When constructing a SequencedWorkerPool, there must be a
147 // MessageLoop on the current thread unless you plan to deliberately
148 // leak it.
150 // Pass the maximum number of threads (they will be lazily created as needed)
151 // and a prefix for the thread name to aid in debugging.
152 SequencedWorkerPool(size_t max_threads,
153 const std::string& thread_name_prefix);
155 // Like above, but with |observer| for testing. Does not take
156 // ownership of |observer|.
157 SequencedWorkerPool(size_t max_threads,
158 const std::string& thread_name_prefix,
159 TestingObserver* observer);
161 // Returns a unique token that can be used to sequence tasks posted to
162 // PostSequencedWorkerTask(). Valid tokens are alwys nonzero.
163 SequenceToken GetSequenceToken();
165 // Returns the sequence token associated with the given name. Calling this
166 // function multiple times with the same string will always produce the
167 // same sequence token. If the name has not been used before, a new token
168 // will be created.
169 SequenceToken GetNamedSequenceToken(const std::string& name);
171 // Returns a SequencedTaskRunner wrapper which posts to this
172 // SequencedWorkerPool using the given sequence token. Tasks with nonzero
173 // delay are posted with SKIP_ON_SHUTDOWN behavior and tasks with zero delay
174 // are posted with BLOCK_SHUTDOWN behavior.
175 scoped_refptr<SequencedTaskRunner> GetSequencedTaskRunner(
176 SequenceToken token);
178 // Returns a SequencedTaskRunner wrapper which posts to this
179 // SequencedWorkerPool using the given sequence token. Tasks with nonzero
180 // delay are posted with SKIP_ON_SHUTDOWN behavior and tasks with zero delay
181 // are posted with the given shutdown behavior.
182 scoped_refptr<SequencedTaskRunner> GetSequencedTaskRunnerWithShutdownBehavior(
183 SequenceToken token,
184 WorkerShutdown shutdown_behavior);
186 // Returns a TaskRunner wrapper which posts to this SequencedWorkerPool using
187 // the given shutdown behavior. Tasks with nonzero delay are posted with
188 // SKIP_ON_SHUTDOWN behavior and tasks with zero delay are posted with the
189 // given shutdown behavior.
190 scoped_refptr<TaskRunner> GetTaskRunnerWithShutdownBehavior(
191 WorkerShutdown shutdown_behavior);
193 // Posts the given task for execution in the worker pool. Tasks posted with
194 // this function will execute in an unspecified order on a background thread.
195 // Returns true if the task was posted. If your tasks have ordering
196 // requirements, see PostSequencedWorkerTask().
198 // This class will attempt to delete tasks that aren't run
199 // (non-block-shutdown semantics) but can't guarantee that this happens. If
200 // all worker threads are busy running CONTINUE_ON_SHUTDOWN tasks, there
201 // will be no workers available to delete these tasks. And there may be
202 // tasks with the same sequence token behind those CONTINUE_ON_SHUTDOWN
203 // tasks. Deleting those tasks before the previous one has completed could
204 // cause nondeterministic crashes because the task could be keeping some
205 // objects alive which do work in their destructor, which could voilate the
206 // assumptions of the running task.
208 // The task will be guaranteed to run to completion before shutdown
209 // (BLOCK_SHUTDOWN semantics).
211 // Returns true if the task was posted successfully. This may fail during
212 // shutdown regardless of the specified ShutdownBehavior.
213 bool PostWorkerTask(const tracked_objects::Location& from_here,
214 const Closure& task);
216 // Same as PostWorkerTask but allows a delay to be specified (although doing
217 // so changes the shutdown behavior). The task will be run after the given
218 // delay has elapsed.
220 // If the delay is nonzero, the task won't be guaranteed to run to completion
221 // before shutdown (SKIP_ON_SHUTDOWN semantics) to avoid shutdown hangs.
222 // If the delay is zero, this behaves exactly like PostWorkerTask, i.e. the
223 // task will be guaranteed to run to completion before shutdown
224 // (BLOCK_SHUTDOWN semantics).
225 bool PostDelayedWorkerTask(const tracked_objects::Location& from_here,
226 const Closure& task,
227 TimeDelta delay);
229 // Same as PostWorkerTask but allows specification of the shutdown behavior.
230 bool PostWorkerTaskWithShutdownBehavior(
231 const tracked_objects::Location& from_here,
232 const Closure& task,
233 WorkerShutdown shutdown_behavior);
235 // Like PostWorkerTask above, but provides sequencing semantics. This means
236 // that tasks posted with the same sequence token (see GetSequenceToken())
237 // are guaranteed to execute in order. This is useful in cases where you're
238 // doing operations that may depend on previous ones, like appending to a
239 // file.
241 // The task will be guaranteed to run to completion before shutdown
242 // (BLOCK_SHUTDOWN semantics).
244 // Returns true if the task was posted successfully. This may fail during
245 // shutdown regardless of the specified ShutdownBehavior.
246 bool PostSequencedWorkerTask(SequenceToken sequence_token,
247 const tracked_objects::Location& from_here,
248 const Closure& task);
250 // Like PostSequencedWorkerTask above, but allows you to specify a named
251 // token, which saves an extra call to GetNamedSequenceToken.
252 bool PostNamedSequencedWorkerTask(const std::string& token_name,
253 const tracked_objects::Location& from_here,
254 const Closure& task);
256 // Same as PostSequencedWorkerTask but allows a delay to be specified
257 // (although doing so changes the shutdown behavior). The task will be run
258 // after the given delay has elapsed.
260 // If the delay is nonzero, the task won't be guaranteed to run to completion
261 // before shutdown (SKIP_ON_SHUTDOWN semantics) to avoid shutdown hangs.
262 // If the delay is zero, this behaves exactly like PostSequencedWorkerTask,
263 // i.e. the task will be guaranteed to run to completion before shutdown
264 // (BLOCK_SHUTDOWN semantics).
265 bool PostDelayedSequencedWorkerTask(
266 SequenceToken sequence_token,
267 const tracked_objects::Location& from_here,
268 const Closure& task,
269 TimeDelta delay);
271 // Same as PostSequencedWorkerTask but allows specification of the shutdown
272 // behavior.
273 bool PostSequencedWorkerTaskWithShutdownBehavior(
274 SequenceToken sequence_token,
275 const tracked_objects::Location& from_here,
276 const Closure& task,
277 WorkerShutdown shutdown_behavior);
279 // TaskRunner implementation. Forwards to PostDelayedWorkerTask().
280 virtual bool PostDelayedTask(const tracked_objects::Location& from_here,
281 const Closure& task,
282 TimeDelta delay) OVERRIDE;
283 virtual bool RunsTasksOnCurrentThread() const OVERRIDE;
285 // Returns true if the current thread is processing a task with the given
286 // sequence_token.
287 bool IsRunningSequenceOnCurrentThread(SequenceToken sequence_token) const;
289 // Blocks until all pending tasks are complete. This should only be called in
290 // unit tests when you want to validate something that should have happened.
291 // This will not flush delayed tasks; delayed tasks get deleted.
293 // Note that calling this will not prevent other threads from posting work to
294 // the queue while the calling thread is waiting on Flush(). In this case,
295 // Flush will return only when there's no more work in the queue. Normally,
296 // this doesn't come up since in a test, all the work is being posted from
297 // the main thread.
298 void FlushForTesting();
300 // Spuriously signal that there is work to be done.
301 void SignalHasWorkForTesting();
303 // Implements the worker pool shutdown. This should be called during app
304 // shutdown, and will discard/join with appropriate tasks before returning.
305 // After this call, subsequent calls to post tasks will fail.
307 // Must be called from the same thread this object was constructed on.
308 void Shutdown() { Shutdown(0); }
310 // A variant that allows an arbitrary number of new blocking tasks to
311 // be posted during shutdown from within tasks that execute during shutdown.
312 // Only tasks designated as BLOCKING_SHUTDOWN will be allowed, and only if
313 // posted by tasks that are not designated as CONTINUE_ON_SHUTDOWN. Once
314 // the limit is reached, subsequent calls to post task fail in all cases.
316 // Must be called from the same thread this object was constructed on.
317 void Shutdown(int max_new_blocking_tasks_after_shutdown);
319 protected:
320 virtual ~SequencedWorkerPool();
322 virtual void OnDestruct() const OVERRIDE;
324 private:
325 friend class RefCountedThreadSafe<SequencedWorkerPool>;
326 friend class DeleteHelper<SequencedWorkerPool>;
328 class Inner;
329 class Worker;
331 const scoped_refptr<MessageLoopProxy> constructor_message_loop_;
333 // Avoid pulling in too many headers by putting (almost) everything
334 // into |inner_|.
335 const scoped_ptr<Inner> inner_;
337 DISALLOW_COPY_AND_ASSIGN(SequencedWorkerPool);
340 } // namespace base
342 #endif // BASE_THREADING_SEQUENCED_WORKER_POOL_H_