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