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 ///////////////////////////////////////////////////////////////////////////////
58 // Forward declaration for ObserverListThreadSafeTraits.
59 template <class ObserverType
>
60 class ObserverListThreadSafe
;
64 // An UnboundMethod is a wrapper for a method where the actual object is
65 // provided at Run dispatch time.
66 template <class T
, class Method
, class Params
>
69 UnboundMethod(Method m
, const Params
& p
) : m_(m
), p_(p
) {
71 (internal::ParamsUseScopedRefptrCorrectly
<Params
>::value
),
72 badunboundmethodparams
);
74 void Run(T
* obj
) const {
75 DispatchToMethod(obj
, m_
, p_
);
82 } // namespace internal
84 // This class is used to work around VS2005 not accepting:
87 // base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType>>;
89 // Instead of friending the class, we could friend the actual function
90 // which calls delete. However, this ends up being
91 // RefCountedThreadSafe::DeleteInternal(), which is private. So we
92 // define our own templated traits class so we can friend it.
94 struct ObserverListThreadSafeTraits
{
95 static void Destruct(const ObserverListThreadSafe
<T
>* x
) {
100 template <class ObserverType
>
101 class ObserverListThreadSafe
102 : public RefCountedThreadSafe
<
103 ObserverListThreadSafe
<ObserverType
>,
104 ObserverListThreadSafeTraits
<ObserverType
>> {
106 typedef typename ObserverList
<ObserverType
>::NotificationType
109 ObserverListThreadSafe()
110 : type_(ObserverListBase
<ObserverType
>::NOTIFY_ALL
) {}
111 explicit ObserverListThreadSafe(NotificationType type
) : type_(type
) {}
113 // Add an observer to the list. An observer should not be added to
114 // the same list more than once.
115 void AddObserver(ObserverType
* obs
) {
116 // If there is not a current MessageLoop, it is impossible to notify on it,
117 // so do not add the observer.
118 if (!MessageLoop::current())
121 ObserverList
<ObserverType
>* list
= nullptr;
122 PlatformThreadId thread_id
= PlatformThread::CurrentId();
124 AutoLock
lock(list_lock_
);
125 if (observer_lists_
.find(thread_id
) == observer_lists_
.end())
126 observer_lists_
[thread_id
] = new ObserverListContext(type_
);
127 list
= &(observer_lists_
[thread_id
]->list
);
129 list
->AddObserver(obs
);
132 // Remove an observer from the list if it is in the list.
133 // If there are pending notifications in-transit to the observer, they will
135 // If the observer to be removed is in the list, RemoveObserver MUST
136 // be called from the same thread which called AddObserver.
137 void RemoveObserver(ObserverType
* obs
) {
138 ObserverListContext
* context
= nullptr;
139 ObserverList
<ObserverType
>* list
= nullptr;
140 PlatformThreadId thread_id
= PlatformThread::CurrentId();
142 AutoLock
lock(list_lock_
);
143 typename
ObserversListMap::iterator it
= observer_lists_
.find(thread_id
);
144 if (it
== observer_lists_
.end()) {
145 // This will happen if we try to remove an observer on a thread
146 // we never added an observer for.
149 context
= it
->second
;
150 list
= &context
->list
;
152 // If we're about to remove the last observer from the list,
153 // then we can remove this observer_list entirely.
154 if (list
->HasObserver(obs
) && list
->size() == 1)
155 observer_lists_
.erase(it
);
157 list
->RemoveObserver(obs
);
159 // If RemoveObserver is called from a notification, the size will be
160 // nonzero. Instead of deleting here, the NotifyWrapper will delete
161 // when it finishes iterating.
162 if (list
->size() == 0)
166 // Verifies that the list is currently empty (i.e. there are no observers).
167 void AssertEmpty() const {
168 AutoLock
lock(list_lock_
);
169 DCHECK(observer_lists_
.empty());
173 // Make a thread-safe callback to each Observer in the list.
174 // Note, these calls are effectively asynchronous. You cannot assume
175 // that at the completion of the Notify call that all Observers have
176 // been Notified. The notification may still be pending delivery.
177 template <class Method
, class... Params
>
178 void Notify(const tracked_objects::Location
& from_here
,
180 const Params
&... params
) {
181 internal::UnboundMethod
<ObserverType
, Method
, Tuple
<Params
...>> method(
182 m
, MakeTuple(params
...));
184 AutoLock
lock(list_lock_
);
185 for (const auto& entry
: observer_lists_
) {
186 ObserverListContext
* context
= entry
.second
;
187 context
->task_runner
->PostTask(
189 Bind(&ObserverListThreadSafe
<ObserverType
>::template NotifyWrapper
<
190 Method
, Tuple
<Params
...>>,
191 this, context
, method
));
196 // See comment above ObserverListThreadSafeTraits' definition.
197 friend struct ObserverListThreadSafeTraits
<ObserverType
>;
199 struct ObserverListContext
{
200 explicit ObserverListContext(NotificationType type
)
201 : task_runner(ThreadTaskRunnerHandle::Get()), list(type
) {}
203 scoped_refptr
<SingleThreadTaskRunner
> task_runner
;
204 ObserverList
<ObserverType
> list
;
207 DISALLOW_COPY_AND_ASSIGN(ObserverListContext
);
210 ~ObserverListThreadSafe() {
211 STLDeleteValues(&observer_lists_
);
214 // Wrapper which is called to fire the notifications for each thread's
215 // ObserverList. This function MUST be called on the thread which owns
216 // the unsafe ObserverList.
217 template <class Method
, class Params
>
219 ObserverListContext
* context
,
220 const internal::UnboundMethod
<ObserverType
, Method
, Params
>& method
) {
221 // Check that this list still needs notifications.
223 AutoLock
lock(list_lock_
);
224 typename
ObserversListMap::iterator it
=
225 observer_lists_
.find(PlatformThread::CurrentId());
227 // The ObserverList could have been removed already. In fact, it could
228 // have been removed and then re-added! If the master list's loop
229 // does not match this one, then we do not need to finish this
231 if (it
== observer_lists_
.end() || it
->second
!= context
)
236 typename ObserverList
<ObserverType
>::Iterator
it(&context
->list
);
238 while ((obs
= it
.GetNext()) != nullptr)
242 // If there are no more observers on the list, we can now delete it.
243 if (context
->list
.size() == 0) {
245 AutoLock
lock(list_lock_
);
246 // Remove |list| if it's not already removed.
247 // This can happen if multiple observers got removed in a notification.
248 // See http://crbug.com/55725.
249 typename
ObserversListMap::iterator it
=
250 observer_lists_
.find(PlatformThread::CurrentId());
251 if (it
!= observer_lists_
.end() && it
->second
== context
)
252 observer_lists_
.erase(it
);
258 // Key by PlatformThreadId because in tests, clients can attempt to remove
259 // observers without a MessageLoop. If this were keyed by MessageLoop, that
260 // operation would be silently ignored, leaving garbage in the ObserverList.
261 typedef std::map
<PlatformThreadId
, ObserverListContext
*>
264 mutable Lock list_lock_
; // Protects the observer_lists_.
265 ObserversListMap observer_lists_
;
266 const NotificationType type_
;
268 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe
);
273 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_