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/message_loop.h"
17 #include "base/observer_list.h"
18 #include "base/single_thread_task_runner.h"
19 #include "base/stl_util.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/threading/platform_thread.h"
23 ///////////////////////////////////////////////////////////////////////////////
27 // A thread-safe container for a list of observers.
28 // This is similar to the observer_list (see observer_list.h), but it
29 // is more robust for multi-threaded situations.
31 // The following use cases are supported:
32 // * Observers can register for notifications from any thread.
33 // Callbacks to the observer will occur on the same thread where
34 // the observer initially called AddObserver() from.
35 // * Any thread may trigger a notification via Notify().
36 // * Observers can remove themselves from the observer list inside
38 // * If one thread is notifying observers concurrently with an observer
39 // removing itself from the observer list, the notifications will
40 // be silently dropped.
42 // The drawback of the threadsafe observer list is that notifications
43 // are not as real-time as the non-threadsafe version of this class.
44 // Notifications will always be done via PostTask() to another thread,
45 // whereas with the non-thread-safe observer_list, notifications happen
46 // synchronously and immediately.
48 // IMPLEMENTATION NOTES
49 // The ObserverListThreadSafe maintains an ObserverList for each thread
50 // which uses the ThreadSafeObserver. When Notifying the observers,
51 // we simply call PostTask to each registered thread, and then each thread
52 // will notify its regular ObserverList.
54 ///////////////////////////////////////////////////////////////////////////////
56 // Forward declaration for ObserverListThreadSafeTraits.
57 template <class ObserverType
>
58 class ObserverListThreadSafe
;
60 // An UnboundMethod is a wrapper for a method where the actual object is
61 // provided at Run dispatch time.
62 template <class T
, class Method
, class Params
>
65 UnboundMethod(Method m
, const Params
& p
) : m_(m
), p_(p
) {
67 (base::internal::ParamsUseScopedRefptrCorrectly
<Params
>::value
),
68 badunboundmethodparams
);
70 void Run(T
* obj
) const {
71 DispatchToMethod(obj
, m_
, p_
);
78 // This class is used to work around VS2005 not accepting:
81 // base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType> >;
83 // Instead of friending the class, we could friend the actual function
84 // which calls delete. However, this ends up being
85 // RefCountedThreadSafe::DeleteInternal(), which is private. So we
86 // define our own templated traits class so we can friend it.
88 struct ObserverListThreadSafeTraits
{
89 static void Destruct(const ObserverListThreadSafe
<T
>* x
) {
94 template <class ObserverType
>
95 class ObserverListThreadSafe
96 : public base::RefCountedThreadSafe
<
97 ObserverListThreadSafe
<ObserverType
>,
98 ObserverListThreadSafeTraits
<ObserverType
> > {
100 typedef typename ObserverList
<ObserverType
>::NotificationType
103 ObserverListThreadSafe()
104 : type_(ObserverListBase
<ObserverType
>::NOTIFY_ALL
) {}
105 explicit ObserverListThreadSafe(NotificationType type
) : type_(type
) {}
107 // Add an observer to the list. An observer should not be added to
108 // the same list more than once.
109 void AddObserver(ObserverType
* obs
) {
110 // If there is not a current MessageLoop, it is impossible to notify on it,
111 // so do not add the observer.
112 if (!base::MessageLoop::current())
115 ObserverList
<ObserverType
>* list
= nullptr;
116 base::PlatformThreadId thread_id
= base::PlatformThread::CurrentId();
118 base::AutoLock
lock(list_lock_
);
119 if (observer_lists_
.find(thread_id
) == observer_lists_
.end())
120 observer_lists_
[thread_id
] = new ObserverListContext(type_
);
121 list
= &(observer_lists_
[thread_id
]->list
);
123 list
->AddObserver(obs
);
126 // 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
129 // If the observer to be removed is in the list, RemoveObserver MUST
130 // be called from the same thread which called AddObserver.
131 void RemoveObserver(ObserverType
* obs
) {
132 ObserverListContext
* context
= nullptr;
133 ObserverList
<ObserverType
>* list
= nullptr;
134 base::PlatformThreadId thread_id
= base::PlatformThread::CurrentId();
136 base::AutoLock
lock(list_lock_
);
137 typename
ObserversListMap::iterator it
= observer_lists_
.find(thread_id
);
138 if (it
== observer_lists_
.end()) {
139 // This will happen if we try to remove an observer on a thread
140 // we never added an observer for.
143 context
= it
->second
;
144 list
= &context
->list
;
146 // If we're about to remove the last observer from the list,
147 // then we can remove this observer_list entirely.
148 if (list
->HasObserver(obs
) && list
->size() == 1)
149 observer_lists_
.erase(it
);
151 list
->RemoveObserver(obs
);
153 // If RemoveObserver is called from a notification, the size will be
154 // nonzero. Instead of deleting here, the NotifyWrapper will delete
155 // when it finishes iterating.
156 if (list
->size() == 0)
160 // Verifies that the list is currently empty (i.e. there are no observers).
161 void AssertEmpty() const {
162 base::AutoLock
lock(list_lock_
);
163 DCHECK(observer_lists_
.empty());
167 // Make a thread-safe callback to each Observer in the list.
168 // Note, these calls are effectively asynchronous. You cannot assume
169 // that at the completion of the Notify call that all Observers have
170 // been Notified. The notification may still be pending delivery.
171 template <class Method
, class... Params
>
172 void Notify(const tracked_objects::Location
& from_here
,
174 const Params
&... params
) {
175 UnboundMethod
<ObserverType
, Method
, base::Tuple
<Params
...>> method(
176 m
, base::MakeTuple(params
...));
178 base::AutoLock
lock(list_lock_
);
179 for (const auto& entry
: observer_lists_
) {
180 ObserverListContext
* context
= entry
.second
;
181 context
->task_runner
->PostTask(
184 &ObserverListThreadSafe
<ObserverType
>::template NotifyWrapper
<
185 Method
, base::Tuple
<Params
...>>,
186 this, context
, method
));
191 // See comment above ObserverListThreadSafeTraits' definition.
192 friend struct ObserverListThreadSafeTraits
<ObserverType
>;
194 struct ObserverListContext
{
195 explicit ObserverListContext(NotificationType type
)
196 : task_runner(base::ThreadTaskRunnerHandle::Get()), list(type
) {}
198 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
;
199 ObserverList
<ObserverType
> list
;
202 DISALLOW_COPY_AND_ASSIGN(ObserverListContext
);
205 ~ObserverListThreadSafe() {
206 STLDeleteValues(&observer_lists_
);
209 // Wrapper which is called to fire the notifications for each thread's
210 // ObserverList. This function MUST be called on the thread which owns
211 // the unsafe ObserverList.
212 template <class Method
, class Params
>
213 void NotifyWrapper(ObserverListContext
* context
,
214 const UnboundMethod
<ObserverType
, Method
, Params
>& method
) {
215 // Check that this list still needs notifications.
217 base::AutoLock
lock(list_lock_
);
218 typename
ObserversListMap::iterator it
=
219 observer_lists_
.find(base::PlatformThread::CurrentId());
221 // 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
223 // does not match this one, then we do not need to finish this
225 if (it
== observer_lists_
.end() || it
->second
!= context
)
230 typename ObserverList
<ObserverType
>::Iterator
it(&context
->list
);
232 while ((obs
= it
.GetNext()) != nullptr)
236 // If there are no more observers on the list, we can now delete it.
237 if (context
->list
.size() == 0) {
239 base::AutoLock
lock(list_lock_
);
240 // Remove |list| if it's not already removed.
241 // This can happen if multiple observers got removed in a notification.
242 // See http://crbug.com/55725.
243 typename
ObserversListMap::iterator it
=
244 observer_lists_
.find(base::PlatformThread::CurrentId());
245 if (it
!= observer_lists_
.end() && it
->second
== context
)
246 observer_lists_
.erase(it
);
252 // Key by PlatformThreadId because in tests, clients can attempt to remove
253 // observers without a MessageLoop. If this were keyed by MessageLoop, that
254 // operation would be silently ignored, leaving garbage in the ObserverList.
255 typedef std::map
<base::PlatformThreadId
, ObserverListContext
*>
258 mutable base::Lock list_lock_
; // Protects the observer_lists_.
259 ObserversListMap observer_lists_
;
260 const NotificationType type_
;
262 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe
);
265 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_