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_OBSERVER_LIST_THREADSAFE_H_
6 #define BASE_OBSERVER_LIST_THREADSAFE_H_
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/location.h"
14 #include "base/logging.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/message_loop.h"
17 #include "base/message_loop_proxy.h"
18 #include "base/observer_list.h"
19 #include "base/threading/platform_thread.h"
21 ///////////////////////////////////////////////////////////////////////////////
25 // A thread-safe container for a list of observers.
26 // This is similar to the observer_list (see observer_list.h), but it
27 // is more robust for multi-threaded situations.
29 // The following use cases are supported:
30 // * Observers can register for notifications from any thread.
31 // Callbacks to the observer will occur on the same thread where
32 // the observer initially called AddObserver() from.
33 // * Any thread may trigger a notification via Notify().
34 // * Observers can remove themselves from the observer list inside
36 // * If one thread is notifying observers concurrently with an observer
37 // removing itself from the observer list, the notifications will
38 // be silently dropped.
40 // The drawback of the threadsafe observer list is that notifications
41 // are not as real-time as the non-threadsafe version of this class.
42 // Notifications will always be done via PostTask() to another thread,
43 // whereas with the non-thread-safe observer_list, notifications happen
44 // synchronously and immediately.
46 // IMPLEMENTATION NOTES
47 // The ObserverListThreadSafe maintains an ObserverList for each thread
48 // which uses the ThreadSafeObserver. When Notifying the observers,
49 // we simply call PostTask to each registered thread, and then each thread
50 // will notify its regular ObserverList.
52 ///////////////////////////////////////////////////////////////////////////////
54 // Forward declaration for ObserverListThreadSafeTraits.
55 template <class ObserverType
>
56 class ObserverListThreadSafe
;
58 // An UnboundMethod is a wrapper for a method where the actual object is
59 // provided at Run dispatch time.
60 template <class T
, class Method
, class Params
>
63 UnboundMethod(Method m
, const Params
& p
) : m_(m
), p_(p
) {
65 (base::internal::ParamsUseScopedRefptrCorrectly
<Params
>::value
),
66 badunboundmethodparams
);
68 void Run(T
* obj
) const {
69 DispatchToMethod(obj
, m_
, p_
);
76 // This class is used to work around VS2005 not accepting:
79 // base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType> >;
81 // Instead of friending the class, we could friend the actual function
82 // which calls delete. However, this ends up being
83 // RefCountedThreadSafe::DeleteInternal(), which is private. So we
84 // define our own templated traits class so we can friend it.
86 struct ObserverListThreadSafeTraits
{
87 static void Destruct(const ObserverListThreadSafe
<T
>* x
) {
92 template <class ObserverType
>
93 class ObserverListThreadSafe
94 : public base::RefCountedThreadSafe
<
95 ObserverListThreadSafe
<ObserverType
>,
96 ObserverListThreadSafeTraits
<ObserverType
> > {
98 typedef typename ObserverList
<ObserverType
>::NotificationType
101 ObserverListThreadSafe()
102 : type_(ObserverListBase
<ObserverType
>::NOTIFY_ALL
) {}
103 explicit ObserverListThreadSafe(NotificationType type
) : type_(type
) {}
105 // Add an observer to the list. An observer should not be added to
106 // the same list more than once.
107 void AddObserver(ObserverType
* obs
) {
108 // If there is not a current MessageLoop, it is impossible to notify on it,
109 // so do not add the observer.
110 if (!MessageLoop::current())
113 ObserverList
<ObserverType
>* list
= NULL
;
114 base::PlatformThreadId thread_id
= base::PlatformThread::CurrentId();
116 base::AutoLock
lock(list_lock_
);
117 if (observer_lists_
.find(thread_id
) == observer_lists_
.end())
118 observer_lists_
[thread_id
] = new ObserverListContext(type_
);
119 list
= &(observer_lists_
[thread_id
]->list
);
121 list
->AddObserver(obs
);
124 // Remove an observer from the list if it is in the list.
125 // If there are pending notifications in-transit to the observer, they will
127 // If the observer to be removed is in the list, RemoveObserver MUST
128 // be called from the same thread which called AddObserver.
129 void RemoveObserver(ObserverType
* obs
) {
130 ObserverListContext
* context
= NULL
;
131 ObserverList
<ObserverType
>* list
= NULL
;
132 base::PlatformThreadId thread_id
= base::PlatformThread::CurrentId();
134 base::AutoLock
lock(list_lock_
);
135 typename
ObserversListMap::iterator it
= observer_lists_
.find(thread_id
);
136 if (it
== observer_lists_
.end()) {
137 // This will happen if we try to remove an observer on a thread
138 // we never added an observer for.
141 context
= it
->second
;
142 list
= &context
->list
;
144 // If we're about to remove the last observer from the list,
145 // then we can remove this observer_list entirely.
146 if (list
->HasObserver(obs
) && list
->size() == 1)
147 observer_lists_
.erase(it
);
149 list
->RemoveObserver(obs
);
151 // If RemoveObserver is called from a notification, the size will be
152 // nonzero. Instead of deleting here, the NotifyWrapper will delete
153 // when it finishes iterating.
154 if (list
->size() == 0)
158 // Verifies that the list is currently empty (i.e. there are no observers).
159 void AssertEmpty() const {
160 base::AutoLock
lock(list_lock_
);
161 DCHECK(observer_lists_
.empty());
165 // Make a thread-safe callback to each Observer in the list.
166 // Note, these calls are effectively asynchronous. You cannot assume
167 // that at the completion of the Notify call that all Observers have
168 // been Notified. The notification may still be pending delivery.
169 template <class Method
>
170 void Notify(Method m
) {
171 UnboundMethod
<ObserverType
, Method
, Tuple0
> method(m
, MakeTuple());
172 Notify
<Method
, Tuple0
>(method
);
175 template <class Method
, class A
>
176 void Notify(Method m
, const A
& a
) {
177 UnboundMethod
<ObserverType
, Method
, Tuple1
<A
> > method(m
, MakeTuple(a
));
178 Notify
<Method
, Tuple1
<A
> >(method
);
181 template <class Method
, class A
, class B
>
182 void Notify(Method m
, const A
& a
, const B
& b
) {
183 UnboundMethod
<ObserverType
, Method
, Tuple2
<A
, B
> > method(
185 Notify
<Method
, Tuple2
<A
, B
> >(method
);
188 template <class Method
, class A
, class B
, class C
>
189 void Notify(Method m
, const A
& a
, const B
& b
, const C
& c
) {
190 UnboundMethod
<ObserverType
, Method
, Tuple3
<A
, B
, C
> > method(
191 m
, MakeTuple(a
, b
, c
));
192 Notify
<Method
, Tuple3
<A
, B
, C
> >(method
);
195 template <class Method
, class A
, class B
, class C
, class D
>
196 void Notify(Method m
, const A
& a
, const B
& b
, const C
& c
, const D
& d
) {
197 UnboundMethod
<ObserverType
, Method
, Tuple4
<A
, B
, C
, D
> > method(
198 m
, MakeTuple(a
, b
, c
, d
));
199 Notify
<Method
, Tuple4
<A
, B
, C
, D
> >(method
);
202 // TODO(mbelshe): Add more wrappers for Notify() with more arguments.
205 // See comment above ObserverListThreadSafeTraits' definition.
206 friend struct ObserverListThreadSafeTraits
<ObserverType
>;
208 struct ObserverListContext
{
209 explicit ObserverListContext(NotificationType type
)
210 : loop(base::MessageLoopProxy::current()),
214 scoped_refptr
<base::MessageLoopProxy
> loop
;
215 ObserverList
<ObserverType
> list
;
217 DISALLOW_COPY_AND_ASSIGN(ObserverListContext
);
220 ~ObserverListThreadSafe() {
221 typename
ObserversListMap::const_iterator it
;
222 for (it
= observer_lists_
.begin(); it
!= observer_lists_
.end(); ++it
)
224 observer_lists_
.clear();
227 template <class Method
, class Params
>
228 void Notify(const UnboundMethod
<ObserverType
, Method
, Params
>& method
) {
229 base::AutoLock
lock(list_lock_
);
230 typename
ObserversListMap::iterator it
;
231 for (it
= observer_lists_
.begin(); it
!= observer_lists_
.end(); ++it
) {
232 ObserverListContext
* context
= (*it
).second
;
233 context
->loop
->PostTask(
235 base::Bind(&ObserverListThreadSafe
<ObserverType
>::
236 template NotifyWrapper
<Method
, Params
>, this, context
, method
));
240 // Wrapper which is called to fire the notifications for each thread's
241 // ObserverList. This function MUST be called on the thread which owns
242 // the unsafe ObserverList.
243 template <class Method
, class Params
>
244 void NotifyWrapper(ObserverListContext
* context
,
245 const UnboundMethod
<ObserverType
, Method
, Params
>& method
) {
247 // Check that this list still needs notifications.
249 base::AutoLock
lock(list_lock_
);
250 typename
ObserversListMap::iterator it
=
251 observer_lists_
.find(base::PlatformThread::CurrentId());
253 // The ObserverList could have been removed already. In fact, it could
254 // have been removed and then re-added! If the master list's loop
255 // does not match this one, then we do not need to finish this
257 if (it
== observer_lists_
.end() || it
->second
!= context
)
262 typename ObserverList
<ObserverType
>::Iterator
it(context
->list
);
264 while ((obs
= it
.GetNext()) != NULL
)
268 // If there are no more observers on the list, we can now delete it.
269 if (context
->list
.size() == 0) {
271 base::AutoLock
lock(list_lock_
);
272 // Remove |list| if it's not already removed.
273 // This can happen if multiple observers got removed in a notification.
274 // See http://crbug.com/55725.
275 typename
ObserversListMap::iterator it
=
276 observer_lists_
.find(base::PlatformThread::CurrentId());
277 if (it
!= observer_lists_
.end() && it
->second
== context
)
278 observer_lists_
.erase(it
);
284 // Key by PlatformThreadId because in tests, clients can attempt to remove
285 // observers without a MessageLoop. If this were keyed by MessageLoop, that
286 // operation would be silently ignored, leaving garbage in the ObserverList.
287 typedef std::map
<base::PlatformThreadId
, ObserverListContext
*>
290 mutable base::Lock list_lock_
; // Protects the observer_lists_.
291 ObserversListMap observer_lists_
;
292 const NotificationType type_
;
294 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe
);
297 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_