Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(71)

Side by Side Diff: base/observer_list_threadsafe.h

Issue 1152983004: Move ObserverList to base namespace. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/observer_list.h ('k') | cc/animation/layer_animation_controller.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef BASE_OBSERVER_LIST_THREADSAFE_H_ 5 #ifndef BASE_OBSERVER_LIST_THREADSAFE_H_
6 #define BASE_OBSERVER_LIST_THREADSAFE_H_ 6 #define BASE_OBSERVER_LIST_THREADSAFE_H_
7 7
8 #include <algorithm> 8 #include <algorithm>
9 #include <map> 9 #include <map>
10 10
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
46 // synchronously and immediately. 46 // synchronously and immediately.
47 // 47 //
48 // IMPLEMENTATION NOTES 48 // IMPLEMENTATION NOTES
49 // The ObserverListThreadSafe maintains an ObserverList for each thread 49 // The ObserverListThreadSafe maintains an ObserverList for each thread
50 // which uses the ThreadSafeObserver. When Notifying the observers, 50 // which uses the ThreadSafeObserver. When Notifying the observers,
51 // we simply call PostTask to each registered thread, and then each thread 51 // we simply call PostTask to each registered thread, and then each thread
52 // will notify its regular ObserverList. 52 // will notify its regular ObserverList.
53 // 53 //
54 /////////////////////////////////////////////////////////////////////////////// 54 ///////////////////////////////////////////////////////////////////////////////
55 55
56 namespace base {
57
56 // Forward declaration for ObserverListThreadSafeTraits. 58 // Forward declaration for ObserverListThreadSafeTraits.
57 template <class ObserverType> 59 template <class ObserverType>
58 class ObserverListThreadSafe; 60 class ObserverListThreadSafe;
59 61
62 namespace internal {
63
60 // An UnboundMethod is a wrapper for a method where the actual object is 64 // An UnboundMethod is a wrapper for a method where the actual object is
61 // provided at Run dispatch time. 65 // provided at Run dispatch time.
62 template <class T, class Method, class Params> 66 template <class T, class Method, class Params>
63 class UnboundMethod { 67 class UnboundMethod {
64 public: 68 public:
65 UnboundMethod(Method m, const Params& p) : m_(m), p_(p) { 69 UnboundMethod(Method m, const Params& p) : m_(m), p_(p) {
66 COMPILE_ASSERT( 70 COMPILE_ASSERT(
67 (base::internal::ParamsUseScopedRefptrCorrectly<Params>::value), 71 (internal::ParamsUseScopedRefptrCorrectly<Params>::value),
68 badunboundmethodparams); 72 badunboundmethodparams);
69 } 73 }
70 void Run(T* obj) const { 74 void Run(T* obj) const {
71 DispatchToMethod(obj, m_, p_); 75 DispatchToMethod(obj, m_, p_);
72 } 76 }
73 private: 77 private:
74 Method m_; 78 Method m_;
75 Params p_; 79 Params p_;
76 }; 80 };
77 81
82 } // namespace internal
83
78 // This class is used to work around VS2005 not accepting: 84 // This class is used to work around VS2005 not accepting:
79 // 85 //
80 // friend class 86 // friend class
81 // base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType> >; 87 // base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType>>;
82 // 88 //
83 // Instead of friending the class, we could friend the actual function 89 // Instead of friending the class, we could friend the actual function
84 // which calls delete. However, this ends up being 90 // which calls delete. However, this ends up being
85 // RefCountedThreadSafe::DeleteInternal(), which is private. So we 91 // RefCountedThreadSafe::DeleteInternal(), which is private. So we
86 // define our own templated traits class so we can friend it. 92 // define our own templated traits class so we can friend it.
87 template <class T> 93 template <class T>
88 struct ObserverListThreadSafeTraits { 94 struct ObserverListThreadSafeTraits {
89 static void Destruct(const ObserverListThreadSafe<T>* x) { 95 static void Destruct(const ObserverListThreadSafe<T>* x) {
90 delete x; 96 delete x;
91 } 97 }
92 }; 98 };
93 99
94 template <class ObserverType> 100 template <class ObserverType>
95 class ObserverListThreadSafe 101 class ObserverListThreadSafe
96 : public base::RefCountedThreadSafe< 102 : public RefCountedThreadSafe<
97 ObserverListThreadSafe<ObserverType>, 103 ObserverListThreadSafe<ObserverType>,
98 ObserverListThreadSafeTraits<ObserverType> > { 104 ObserverListThreadSafeTraits<ObserverType>> {
99 public: 105 public:
100 typedef typename ObserverList<ObserverType>::NotificationType 106 typedef typename ObserverList<ObserverType>::NotificationType
101 NotificationType; 107 NotificationType;
102 108
103 ObserverListThreadSafe() 109 ObserverListThreadSafe()
104 : type_(ObserverListBase<ObserverType>::NOTIFY_ALL) {} 110 : type_(ObserverListBase<ObserverType>::NOTIFY_ALL) {}
105 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {} 111 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {}
106 112
107 // Add an observer to the list. An observer should not be added to 113 // Add an observer to the list. An observer should not be added to
108 // the same list more than once. 114 // the same list more than once.
109 void AddObserver(ObserverType* obs) { 115 void AddObserver(ObserverType* obs) {
110 // If there is not a current MessageLoop, it is impossible to notify on it, 116 // If there is not a current MessageLoop, it is impossible to notify on it,
111 // so do not add the observer. 117 // so do not add the observer.
112 if (!base::MessageLoop::current()) 118 if (!MessageLoop::current())
113 return; 119 return;
114 120
115 ObserverList<ObserverType>* list = nullptr; 121 ObserverList<ObserverType>* list = nullptr;
116 base::PlatformThreadId thread_id = base::PlatformThread::CurrentId(); 122 PlatformThreadId thread_id = PlatformThread::CurrentId();
117 { 123 {
118 base::AutoLock lock(list_lock_); 124 AutoLock lock(list_lock_);
119 if (observer_lists_.find(thread_id) == observer_lists_.end()) 125 if (observer_lists_.find(thread_id) == observer_lists_.end())
120 observer_lists_[thread_id] = new ObserverListContext(type_); 126 observer_lists_[thread_id] = new ObserverListContext(type_);
121 list = &(observer_lists_[thread_id]->list); 127 list = &(observer_lists_[thread_id]->list);
122 } 128 }
123 list->AddObserver(obs); 129 list->AddObserver(obs);
124 } 130 }
125 131
126 // Remove an observer from the list if it is in the list. 132 // Remove an observer from the list if it is in the list.
127 // If there are pending notifications in-transit to the observer, they will 133 // If there are pending notifications in-transit to the observer, they will
128 // be aborted. 134 // be aborted.
129 // If the observer to be removed is in the list, RemoveObserver MUST 135 // If the observer to be removed is in the list, RemoveObserver MUST
130 // be called from the same thread which called AddObserver. 136 // be called from the same thread which called AddObserver.
131 void RemoveObserver(ObserverType* obs) { 137 void RemoveObserver(ObserverType* obs) {
132 ObserverListContext* context = nullptr; 138 ObserverListContext* context = nullptr;
133 ObserverList<ObserverType>* list = nullptr; 139 ObserverList<ObserverType>* list = nullptr;
134 base::PlatformThreadId thread_id = base::PlatformThread::CurrentId(); 140 PlatformThreadId thread_id = PlatformThread::CurrentId();
135 { 141 {
136 base::AutoLock lock(list_lock_); 142 AutoLock lock(list_lock_);
137 typename ObserversListMap::iterator it = observer_lists_.find(thread_id); 143 typename ObserversListMap::iterator it = observer_lists_.find(thread_id);
138 if (it == observer_lists_.end()) { 144 if (it == observer_lists_.end()) {
139 // This will happen if we try to remove an observer on a thread 145 // This will happen if we try to remove an observer on a thread
140 // we never added an observer for. 146 // we never added an observer for.
141 return; 147 return;
142 } 148 }
143 context = it->second; 149 context = it->second;
144 list = &context->list; 150 list = &context->list;
145 151
146 // If we're about to remove the last observer from the list, 152 // If we're about to remove the last observer from the list,
147 // then we can remove this observer_list entirely. 153 // then we can remove this observer_list entirely.
148 if (list->HasObserver(obs) && list->size() == 1) 154 if (list->HasObserver(obs) && list->size() == 1)
149 observer_lists_.erase(it); 155 observer_lists_.erase(it);
150 } 156 }
151 list->RemoveObserver(obs); 157 list->RemoveObserver(obs);
152 158
153 // If RemoveObserver is called from a notification, the size will be 159 // If RemoveObserver is called from a notification, the size will be
154 // nonzero. Instead of deleting here, the NotifyWrapper will delete 160 // nonzero. Instead of deleting here, the NotifyWrapper will delete
155 // when it finishes iterating. 161 // when it finishes iterating.
156 if (list->size() == 0) 162 if (list->size() == 0)
157 delete context; 163 delete context;
158 } 164 }
159 165
160 // Verifies that the list is currently empty (i.e. there are no observers). 166 // Verifies that the list is currently empty (i.e. there are no observers).
161 void AssertEmpty() const { 167 void AssertEmpty() const {
162 base::AutoLock lock(list_lock_); 168 AutoLock lock(list_lock_);
163 DCHECK(observer_lists_.empty()); 169 DCHECK(observer_lists_.empty());
164 } 170 }
165 171
166 // Notify methods. 172 // Notify methods.
167 // Make a thread-safe callback to each Observer in the list. 173 // Make a thread-safe callback to each Observer in the list.
168 // Note, these calls are effectively asynchronous. You cannot assume 174 // Note, these calls are effectively asynchronous. You cannot assume
169 // that at the completion of the Notify call that all Observers have 175 // that at the completion of the Notify call that all Observers have
170 // been Notified. The notification may still be pending delivery. 176 // been Notified. The notification may still be pending delivery.
171 template <class Method, class... Params> 177 template <class Method, class... Params>
172 void Notify(const tracked_objects::Location& from_here, 178 void Notify(const tracked_objects::Location& from_here,
173 Method m, 179 Method m,
174 const Params&... params) { 180 const Params&... params) {
175 UnboundMethod<ObserverType, Method, base::Tuple<Params...>> method( 181 internal::UnboundMethod<ObserverType, Method, Tuple<Params...>> method(
176 m, base::MakeTuple(params...)); 182 m, MakeTuple(params...));
177 183
178 base::AutoLock lock(list_lock_); 184 AutoLock lock(list_lock_);
179 for (const auto& entry : observer_lists_) { 185 for (const auto& entry : observer_lists_) {
180 ObserverListContext* context = entry.second; 186 ObserverListContext* context = entry.second;
181 context->task_runner->PostTask( 187 context->task_runner->PostTask(
182 from_here, 188 from_here,
183 base::Bind( 189 Bind(&ObserverListThreadSafe<ObserverType>::template NotifyWrapper<
184 &ObserverListThreadSafe<ObserverType>::template NotifyWrapper< 190 Method, Tuple<Params...>>,
185 Method, base::Tuple<Params...>>,
186 this, context, method)); 191 this, context, method));
187 } 192 }
188 } 193 }
189 194
190 private: 195 private:
191 // See comment above ObserverListThreadSafeTraits' definition. 196 // See comment above ObserverListThreadSafeTraits' definition.
192 friend struct ObserverListThreadSafeTraits<ObserverType>; 197 friend struct ObserverListThreadSafeTraits<ObserverType>;
193 198
194 struct ObserverListContext { 199 struct ObserverListContext {
195 explicit ObserverListContext(NotificationType type) 200 explicit ObserverListContext(NotificationType type)
196 : task_runner(base::ThreadTaskRunnerHandle::Get()), list(type) {} 201 : task_runner(ThreadTaskRunnerHandle::Get()), list(type) {}
197 202
198 scoped_refptr<base::SingleThreadTaskRunner> task_runner; 203 scoped_refptr<SingleThreadTaskRunner> task_runner;
199 ObserverList<ObserverType> list; 204 ObserverList<ObserverType> list;
200 205
201 private: 206 private:
202 DISALLOW_COPY_AND_ASSIGN(ObserverListContext); 207 DISALLOW_COPY_AND_ASSIGN(ObserverListContext);
203 }; 208 };
204 209
205 ~ObserverListThreadSafe() { 210 ~ObserverListThreadSafe() {
206 STLDeleteValues(&observer_lists_); 211 STLDeleteValues(&observer_lists_);
207 } 212 }
208 213
209 // Wrapper which is called to fire the notifications for each thread's 214 // Wrapper which is called to fire the notifications for each thread's
210 // ObserverList. This function MUST be called on the thread which owns 215 // ObserverList. This function MUST be called on the thread which owns
211 // the unsafe ObserverList. 216 // the unsafe ObserverList.
212 template <class Method, class Params> 217 template <class Method, class Params>
213 void NotifyWrapper(ObserverListContext* context, 218 void NotifyWrapper(
214 const UnboundMethod<ObserverType, Method, Params>& method) { 219 ObserverListContext* context,
220 const internal::UnboundMethod<ObserverType, Method, Params>& method) {
215 // Check that this list still needs notifications. 221 // Check that this list still needs notifications.
216 { 222 {
217 base::AutoLock lock(list_lock_); 223 AutoLock lock(list_lock_);
218 typename ObserversListMap::iterator it = 224 typename ObserversListMap::iterator it =
219 observer_lists_.find(base::PlatformThread::CurrentId()); 225 observer_lists_.find(PlatformThread::CurrentId());
220 226
221 // The ObserverList could have been removed already. In fact, it could 227 // The ObserverList could have been removed already. In fact, it could
222 // have been removed and then re-added! If the master list's loop 228 // have been removed and then re-added! If the master list's loop
223 // does not match this one, then we do not need to finish this 229 // does not match this one, then we do not need to finish this
224 // notification. 230 // notification.
225 if (it == observer_lists_.end() || it->second != context) 231 if (it == observer_lists_.end() || it->second != context)
226 return; 232 return;
227 } 233 }
228 234
229 { 235 {
230 typename ObserverList<ObserverType>::Iterator it(&context->list); 236 typename ObserverList<ObserverType>::Iterator it(&context->list);
231 ObserverType* obs; 237 ObserverType* obs;
232 while ((obs = it.GetNext()) != nullptr) 238 while ((obs = it.GetNext()) != nullptr)
233 method.Run(obs); 239 method.Run(obs);
234 } 240 }
235 241
236 // If there are no more observers on the list, we can now delete it. 242 // If there are no more observers on the list, we can now delete it.
237 if (context->list.size() == 0) { 243 if (context->list.size() == 0) {
238 { 244 {
239 base::AutoLock lock(list_lock_); 245 AutoLock lock(list_lock_);
240 // Remove |list| if it's not already removed. 246 // Remove |list| if it's not already removed.
241 // This can happen if multiple observers got removed in a notification. 247 // This can happen if multiple observers got removed in a notification.
242 // See http://crbug.com/55725. 248 // See http://crbug.com/55725.
243 typename ObserversListMap::iterator it = 249 typename ObserversListMap::iterator it =
244 observer_lists_.find(base::PlatformThread::CurrentId()); 250 observer_lists_.find(PlatformThread::CurrentId());
245 if (it != observer_lists_.end() && it->second == context) 251 if (it != observer_lists_.end() && it->second == context)
246 observer_lists_.erase(it); 252 observer_lists_.erase(it);
247 } 253 }
248 delete context; 254 delete context;
249 } 255 }
250 } 256 }
251 257
252 // Key by PlatformThreadId because in tests, clients can attempt to remove 258 // Key by PlatformThreadId because in tests, clients can attempt to remove
253 // observers without a MessageLoop. If this were keyed by MessageLoop, that 259 // observers without a MessageLoop. If this were keyed by MessageLoop, that
254 // operation would be silently ignored, leaving garbage in the ObserverList. 260 // operation would be silently ignored, leaving garbage in the ObserverList.
255 typedef std::map<base::PlatformThreadId, ObserverListContext*> 261 typedef std::map<PlatformThreadId, ObserverListContext*>
256 ObserversListMap; 262 ObserversListMap;
257 263
258 mutable base::Lock list_lock_; // Protects the observer_lists_. 264 mutable Lock list_lock_; // Protects the observer_lists_.
259 ObserversListMap observer_lists_; 265 ObserversListMap observer_lists_;
260 const NotificationType type_; 266 const NotificationType type_;
261 267
262 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe); 268 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe);
263 }; 269 };
264 270
271 } // namespace base
272
273 // TODO(brettw) remove this when callers use the correct namespace.
274 using base::ObserverListThreadSafe;
275
265 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_ 276 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_
OLDNEW
« no previous file with comments | « base/observer_list.h ('k') | cc/animation/layer_animation_controller.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698