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 <memory>
9#include <string>
10#include <utility>
11
12#include "base/callback.h"
13#include "base/location.h"
14#include "base/logging.h"
15#include "base/macros.h"
16#include "base/memory/scoped_refptr.h"
17#include "base/single_thread_task_runner.h"
18#include "base/task_runner_util.h"
19#include "base/time/time.h"
20#include "content/common/content_export.h"
21
22namespace content {
23
24class BrowserThreadDelegate;
25class BrowserThreadImpl;
26
27// Use DCHECK_CURRENTLY_ON(BrowserThread::ID) to assert that a function can only
28// be called on the named BrowserThread.
29#define DCHECK_CURRENTLY_ON(thread_identifier) \
30 (DCHECK(::content::BrowserThread::CurrentlyOn(thread_identifier)) \
31 << ::content::BrowserThread::GetDCheckCurrentlyOnErrorMessage( \
32 thread_identifier))
33
34///////////////////////////////////////////////////////////////////////////////
35// BrowserThread
36//
37// Utility functions for threads that are known by a browser-wide name. For
38// example, there is one IO thread for the entire browser process, and various
39// pieces of code find it useful to retrieve a pointer to the IO thread's
40// message loop.
41//
42// See browser_task_traits.h for posting Tasks to a BrowserThread.
43//
44// This class automatically handles the lifetime of different threads. You
45// should never need to cache pointers to MessageLoops, since they're not thread
46// safe.
47class CONTENT_EXPORT BrowserThread {
48 public:
49 // An enumeration of the well-known threads.
50 // NOTE: threads must be listed in the order of their life-time, with each
51 // thread outliving every other thread below it.
52 enum ID {
53 // The main thread in the browser.
54 UI,
55
56 // This is the thread that processes non-blocking IO, i.e. IPC and network.
57 // Blocking I/O should happen in ThreadPool.
58 IO,
59
60 // NOTE: do not add new threads here. Instead you should just use
61 // base::Create*TaskRunnerWithTraits to run tasks on the ThreadPool.
62
63 // This identifier does not represent a thread. Instead it counts the
64 // number of well-known threads. Insert new well-known threads before this
65 // identifier.
66 ID_COUNT
67 };
68
69 // NOTE: Task posting APIs have moved to post_task.h. See
70 // browser_task_traits.h.
71
72 // TODO(crbug.com/878356): Consider replacing callsites of this with
73 // base::CreateTaskRunnerWithTraits({id})->DeleteSoon(..).
74 template <class T>
75 static bool DeleteSoon(ID identifier,
76 const base::Location& from_here,
77 const T* object) {
78 return GetTaskRunnerForThread(identifier)->DeleteSoon(from_here, object);
79 }
80
81 template <class T>
82 static bool DeleteSoon(ID identifier,
83 const base::Location& from_here,
84 std::unique_ptr<T> object) {
85 return DeleteSoon(identifier, from_here, object.release());
86 }
87
88 template <class T>
89 static void ReleaseSoon(ID identifier,
90 const base::Location& from_here,
91 scoped_refptr<T>&& object) {
92 GetTaskRunnerForThread(identifier)
93 ->ReleaseSoon(from_here, std::move(object));
94 }
95
96 // For use with scheduling non-critical tasks for execution after startup.
97 // The order or execution of tasks posted here is unspecified even when
98 // posting to a SequencedTaskRunner and tasks are not guaranteed to be run
99 // prior to browser shutdown.
100 // When called after the browser startup is complete, will post |task|
101 // to |task_runner| immediately.
102 // Note: see related ContentBrowserClient::PostAfterStartupTask.
103 //
104 // TODO(crbug.com/887407): Replace callsites with PostTaskWithTraits and
105 // appropriate traits (TBD).
106 static void PostAfterStartupTask(
107 const base::Location& from_here,
108 const scoped_refptr<base::TaskRunner>& task_runner,
109 base::OnceClosure task);
110
111 // Callable on any thread. Returns whether the given well-known thread is
112 // initialized.
113 static bool IsThreadInitialized(ID identifier) WARN_UNUSED_RESULT;
114
115 // Callable on any thread. Returns whether you're currently on a particular
116 // thread. To DCHECK this, use the DCHECK_CURRENTLY_ON() macro above.
117 static bool CurrentlyOn(ID identifier) WARN_UNUSED_RESULT;
118
119 // If the current message loop is one of the known threads, returns true and
120 // sets identifier to its ID. Otherwise returns false.
121 static bool GetCurrentThreadIdentifier(ID* identifier) WARN_UNUSED_RESULT;
122
123 // Sets the delegate for BrowserThread::IO.
124 //
125 // Only one delegate may be registered at a time. The delegate may be
126 // unregistered by providing a nullptr pointer.
127 //
128 // The delegate can only be registered through this call before
129 // BrowserThreadImpl(BrowserThread::IO) is created and unregistered after
130 // it was destroyed and its underlying thread shutdown.
131 static void SetIOThreadDelegate(BrowserThreadDelegate* delegate);
132
133 // Use these templates in conjunction with RefCountedThreadSafe or scoped_ptr
134 // when you want to ensure that an object is deleted on a specific thread.
135 // This is needed when an object can hop between threads (i.e. UI -> IO ->
136 // UI), and thread switching delays can mean that the final UI tasks executes
137 // before the IO task's stack unwinds. This would lead to the object
138 // destructing on the IO thread, which often is not what you want (i.e. to
139 // unregister from NotificationService, to notify other objects on the
140 // creating thread etc). Note: see base::OnTaskRunnerDeleter and
141 // base::RefCountedDeleteOnSequence to bind to SequencedTaskRunner instead of
142 // specific BrowserThreads.
143 template <ID thread>
144 struct DeleteOnThread {
145 template <typename T>
146 static void Destruct(const T* x) {
147 if (CurrentlyOn(thread)) {
148 delete x;
149 } else {
150 if (!DeleteSoon(thread, FROM_HERE, x)) {
151#if defined(UNIT_TEST)
152 // Only logged under unit testing because leaks at shutdown
153 // are acceptable under normal circumstances.
154 LOG(ERROR) << "DeleteSoon failed on thread " << thread;
155#endif // UNIT_TEST
156 }
157 }
158 }
159 template <typename T>
160 inline void operator()(T* ptr) const {
161 enum { type_must_be_complete = sizeof(T) };
162 Destruct(ptr);
163 }
164 };
165
166 // Sample usage with RefCountedThreadSafe:
167 // class Foo
168 // : public base::RefCountedThreadSafe<
169 // Foo, BrowserThread::DeleteOnIOThread> {
170 //
171 // ...
172 // private:
173 // friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
174 // friend class base::DeleteHelper<Foo>;
175 //
176 // ~Foo();
177 //
178 // Sample usage with scoped_ptr:
179 // std::unique_ptr<Foo, BrowserThread::DeleteOnIOThread> ptr;
180 //
181 // Note: see base::OnTaskRunnerDeleter and base::RefCountedDeleteOnSequence to
182 // bind to SequencedTaskRunner instead of specific BrowserThreads.
183 struct DeleteOnUIThread : public DeleteOnThread<UI> {};
184 struct DeleteOnIOThread : public DeleteOnThread<IO> {};
185
186 // Returns an appropriate error message for when DCHECK_CURRENTLY_ON() fails.
187 static std::string GetDCheckCurrentlyOnErrorMessage(ID expected);
188
189 // Runs all pending tasks for the given thread. Tasks posted after this method
190 // is called (in particular any task posted from within any of the pending
191 // tasks) will be queued but not run. Conceptually this call will disable all
192 // queues, run any pending tasks, and re-enable all the queues.
193 //
194 // If any of the pending tasks posted a task, these could be run by calling
195 // this method again or running a regular RunLoop. But if that were the case
196 // you should probably rewrite you tests to wait for a specific event instead.
197 //
198 // NOTE: Can only be called from the UI thread.
199 static void RunAllPendingTasksOnThreadForTesting(ID identifier);
200
201 protected:
202 // For DeleteSoon(). Requires that the BrowserThread with the provided
203 // |identifier| was started.
204 static scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunnerForThread(
205 ID identifier);
206
207 private:
208 friend class BrowserThreadImpl;
209
210 BrowserThread() {}
211 DISALLOW_COPY_AND_ASSIGN(BrowserThread);
212};
213
214} // namespace content
215
216#endif // CONTENT_PUBLIC_BROWSER_BROWSER_THREAD_H_
217