Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / content / public / browser / browser_thread.h
bloba68903dab9a59fb245f56ab197894f6251b219b2
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 CONTENT_PUBLIC_BROWSER_BROWSER_THREAD_H_
6 #define CONTENT_PUBLIC_BROWSER_BROWSER_THREAD_H_
8 #include <string>
10 #include "base/basictypes.h"
11 #include "base/callback.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/task_runner_util.h"
16 #include "base/time/time.h"
17 #include "content/common/content_export.h"
19 namespace base {
20 class MessageLoop;
21 class SequencedWorkerPool;
22 class Thread;
25 namespace content {
27 class BrowserThreadDelegate;
28 class BrowserThreadImpl;
30 // Use DCHECK_CURRENTLY_ON(BrowserThread::ID) to assert that a function can only
31 // be called on the named BrowserThread.
32 #define DCHECK_CURRENTLY_ON(thread_identifier) \
33 (DCHECK(::content::BrowserThread::CurrentlyOn(thread_identifier)) \
34 << ::content::BrowserThread::GetDCheckCurrentlyOnErrorMessage( \
35 thread_identifier))
37 ///////////////////////////////////////////////////////////////////////////////
38 // BrowserThread
40 // Utility functions for threads that are known by a browser-wide
41 // name. For example, there is one IO thread for the entire browser
42 // process, and various pieces of code find it useful to retrieve a
43 // pointer to the IO thread's message loop.
45 // Invoke a task by thread ID:
47 // BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, task);
49 // The return value is false if the task couldn't be posted because the target
50 // thread doesn't exist. If this could lead to data loss, you need to check the
51 // result and restructure the code to ensure it doesn't occur.
53 // This class automatically handles the lifetime of different threads.
54 // It's always safe to call PostTask on any thread. If it's not yet created,
55 // the task is deleted. There are no race conditions. If the thread that the
56 // task is posted to is guaranteed to outlive the current thread, then no locks
57 // are used. You should never need to cache pointers to MessageLoops, since
58 // they're not thread safe.
59 class CONTENT_EXPORT BrowserThread {
60 public:
61 // An enumeration of the well-known threads.
62 // NOTE: threads must be listed in the order of their life-time, with each
63 // thread outliving every other thread below it.
64 enum ID {
65 // The main thread in the browser.
66 UI,
68 // This is the thread that interacts with the database.
69 DB,
71 // This is the thread that interacts with the file system.
72 FILE,
74 // Used for file system operations that block user interactions.
75 // Responsiveness of this thread affect users.
76 FILE_USER_BLOCKING,
78 // Used to launch and terminate Chrome processes.
79 PROCESS_LAUNCHER,
81 // This is the thread to handle slow HTTP cache operations.
82 CACHE,
84 // This is the thread that processes non-blocking IO, i.e. IPC and network.
85 // Blocking IO should happen on other threads like DB, FILE,
86 // FILE_USER_BLOCKING and CACHE depending on the usage.
87 IO,
89 // NOTE: do not add new threads here that are only used by a small number of
90 // files. Instead you should just use a Thread class and pass its
91 // task runner around. Named threads there are only for threads that
92 // are used in many places.
94 // This identifier does not represent a thread. Instead it counts the
95 // number of well-known threads. Insert new well-known threads before this
96 // identifier.
97 ID_COUNT
100 // These are the same methods in message_loop.h, but are guaranteed to either
101 // get posted to the MessageLoop if it's still alive, or be deleted otherwise.
102 // They return true iff the thread existed and the task was posted. Note that
103 // even if the task is posted, there's no guarantee that it will run, since
104 // the target thread may already have a Quit message in its queue.
105 static bool PostTask(ID identifier,
106 const tracked_objects::Location& from_here,
107 const base::Closure& task);
108 static bool PostDelayedTask(ID identifier,
109 const tracked_objects::Location& from_here,
110 const base::Closure& task,
111 base::TimeDelta delay);
112 static bool PostNonNestableTask(ID identifier,
113 const tracked_objects::Location& from_here,
114 const base::Closure& task);
115 static bool PostNonNestableDelayedTask(
116 ID identifier,
117 const tracked_objects::Location& from_here,
118 const base::Closure& task,
119 base::TimeDelta delay);
121 static bool PostTaskAndReply(
122 ID identifier,
123 const tracked_objects::Location& from_here,
124 const base::Closure& task,
125 const base::Closure& reply);
127 template <typename ReturnType, typename ReplyArgType>
128 static bool PostTaskAndReplyWithResult(
129 ID identifier,
130 const tracked_objects::Location& from_here,
131 const base::Callback<ReturnType(void)>& task,
132 const base::Callback<void(ReplyArgType)>& reply) {
133 scoped_refptr<base::SingleThreadTaskRunner> task_runner =
134 GetMessageLoopProxyForThread(identifier);
135 return base::PostTaskAndReplyWithResult(task_runner.get(), from_here, task,
136 reply);
139 template <class T>
140 static bool DeleteSoon(ID identifier,
141 const tracked_objects::Location& from_here,
142 const T* object) {
143 return GetMessageLoopProxyForThread(identifier)->DeleteSoon(
144 from_here, object);
147 template <class T>
148 static bool ReleaseSoon(ID identifier,
149 const tracked_objects::Location& from_here,
150 const T* object) {
151 return GetMessageLoopProxyForThread(identifier)->ReleaseSoon(
152 from_here, object);
155 // Simplified wrappers for posting to the blocking thread pool. Use this
156 // for doing things like blocking I/O.
158 // The first variant will run the task in the pool with no sequencing
159 // semantics, so may get run in parallel with other posted tasks. The second
160 // variant will all post a task with no sequencing semantics, and will post a
161 // reply task to the origin TaskRunner upon completion. The third variant
162 // provides sequencing between tasks with the same sequence token name.
164 // These tasks are guaranteed to run before shutdown.
166 // If you need to provide different shutdown semantics (like you have
167 // something slow and noncritical that doesn't need to block shutdown),
168 // or you want to manually provide a sequence token (which saves a map
169 // lookup and is guaranteed unique without you having to come up with a
170 // unique string), you can access the sequenced worker pool directly via
171 // GetBlockingPool().
173 // If you need to PostTaskAndReplyWithResult, use
174 // base::PostTaskAndReplyWithResult() with GetBlockingPool() as the task
175 // runner.
176 static bool PostBlockingPoolTask(const tracked_objects::Location& from_here,
177 const base::Closure& task);
178 static bool PostBlockingPoolTaskAndReply(
179 const tracked_objects::Location& from_here,
180 const base::Closure& task,
181 const base::Closure& reply);
182 static bool PostBlockingPoolSequencedTask(
183 const std::string& sequence_token_name,
184 const tracked_objects::Location& from_here,
185 const base::Closure& task);
187 // For use with scheduling non-critical tasks for execution after startup.
188 // The order or execution of tasks posted here is unspecified even when
189 // posting to a SequencedTaskRunner and tasks are not guaranteed to be run
190 // prior to browser shutdown.
191 // Note: see related ContentBrowserClient::PostAfterStartupTask.
192 static void PostAfterStartupTask(
193 const tracked_objects::Location& from_here,
194 const scoped_refptr<base::TaskRunner>& task_runner,
195 const base::Closure& task);
197 // Returns the thread pool used for blocking file I/O. Use this object to
198 // perform random blocking operations such as file writes or querying the
199 // Windows registry.
200 static base::SequencedWorkerPool* GetBlockingPool() WARN_UNUSED_RESULT;
202 // Callable on any thread. Returns whether the given well-known thread is
203 // initialized.
204 static bool IsThreadInitialized(ID identifier) WARN_UNUSED_RESULT;
206 // Callable on any thread. Returns whether you're currently on a particular
207 // thread. To DCHECK this, use the DCHECK_CURRENTLY_ON() macro above.
208 static bool CurrentlyOn(ID identifier) WARN_UNUSED_RESULT;
210 // Callable on any thread. Returns whether the threads message loop is valid.
211 // If this returns false it means the thread is in the process of shutting
212 // down.
213 static bool IsMessageLoopValid(ID identifier) WARN_UNUSED_RESULT;
215 // If the current message loop is one of the known threads, returns true and
216 // sets identifier to its ID. Otherwise returns false.
217 static bool GetCurrentThreadIdentifier(ID* identifier) WARN_UNUSED_RESULT;
219 // Callers can hold on to a refcounted task runner beyond the lifetime
220 // of the thread.
221 static scoped_refptr<base::SingleThreadTaskRunner>
222 GetMessageLoopProxyForThread(ID identifier);
224 // Returns a pointer to the thread's message loop, which will become
225 // invalid during shutdown, so you probably shouldn't hold onto it.
227 // This must not be called before the thread is started, or after
228 // the thread is stopped, or it will DCHECK.
230 // Ownership remains with the BrowserThread implementation, so you
231 // must not delete the pointer.
232 static base::MessageLoop* UnsafeGetMessageLoopForThread(ID identifier);
234 // Sets the delegate for the specified BrowserThread.
236 // Only one delegate may be registered at a time. Delegates may be
237 // unregistered by providing a nullptr pointer.
239 // If the caller unregisters a delegate before CleanUp has been
240 // called, it must perform its own locking to ensure the delegate is
241 // not deleted while unregistering.
242 static void SetDelegate(ID identifier, BrowserThreadDelegate* delegate);
244 // Use these templates in conjunction with RefCountedThreadSafe or scoped_ptr
245 // when you want to ensure that an object is deleted on a specific thread.
246 // This is needed when an object can hop between threads
247 // (i.e. IO -> FILE -> IO), and thread switching delays can mean that the
248 // final IO tasks executes before the FILE task's stack unwinds.
249 // This would lead to the object destructing on the FILE thread, which often
250 // is not what you want (i.e. to unregister from NotificationService, to
251 // notify other objects on the creating thread etc).
252 template<ID thread>
253 struct DeleteOnThread {
254 template<typename T>
255 static void Destruct(const T* x) {
256 if (CurrentlyOn(thread)) {
257 delete x;
258 } else {
259 if (!DeleteSoon(thread, FROM_HERE, x)) {
260 #if defined(UNIT_TEST)
261 // Only logged under unit testing because leaks at shutdown
262 // are acceptable under normal circumstances.
263 LOG(ERROR) << "DeleteSoon failed on thread " << thread;
264 #endif // UNIT_TEST
268 template <typename T>
269 inline void operator()(T* ptr) const {
270 enum { type_must_be_complete = sizeof(T) };
271 Destruct(ptr);
275 // Sample usage with RefCountedThreadSafe:
276 // class Foo
277 // : public base::RefCountedThreadSafe<
278 // Foo, BrowserThread::DeleteOnIOThread> {
280 // ...
281 // private:
282 // friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
283 // friend class base::DeleteHelper<Foo>;
285 // ~Foo();
287 // Sample usage with scoped_ptr:
288 // scoped_ptr<Foo, BrowserThread::DeleteOnIOThread> ptr;
289 struct DeleteOnUIThread : public DeleteOnThread<UI> { };
290 struct DeleteOnIOThread : public DeleteOnThread<IO> { };
291 struct DeleteOnFileThread : public DeleteOnThread<FILE> { };
292 struct DeleteOnDBThread : public DeleteOnThread<DB> { };
294 // Returns an appropriate error message for when DCHECK_CURRENTLY_ON() fails.
295 static std::string GetDCheckCurrentlyOnErrorMessage(ID expected);
297 private:
298 friend class BrowserThreadImpl;
300 BrowserThread() {}
301 DISALLOW_COPY_AND_ASSIGN(BrowserThread);
304 } // namespace content
306 #endif // CONTENT_PUBLIC_BROWSER_BROWSER_THREAD_H_