blob: b9b4a624ca815da9efdf4d72423516b03f4637b6 [file] [log] [blame]
jhawkins@chromium.org4a310212012-01-04 04:36:57 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
mbelshe@google.com877d2032008-10-23 08:09:21 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_OBSERVER_LIST_THREADSAFE_H_
6#define BASE_OBSERVER_LIST_THREADSAFE_H_
7
erg@chromium.org6f206e72010-07-15 03:58:17 +09008#include <algorithm>
erg@chromium.orga7528522010-07-16 02:23:23 +09009#include <map>
mbelshe@google.com877d2032008-10-23 08:09:21 +090010
11#include "base/basictypes.h"
jhawkins@chromium.org22d67562011-10-13 05:26:50 +090012#include "base/bind.h"
ajwong@chromium.org8e2e3002011-09-22 03:05:41 +090013#include "base/location.h"
mbelshe@google.com877d2032008-10-23 08:09:21 +090014#include "base/logging.h"
levin@chromium.org5c528682011-03-28 10:54:15 +090015#include "base/memory/ref_counted.h"
avi@chromium.orga043a862013-07-18 17:12:40 +090016#include "base/message_loop/message_loop.h"
mbelshe@google.com877d2032008-10-23 08:09:21 +090017#include "base/observer_list.h"
skyostil97aefe12015-05-01 04:06:15 +090018#include "base/single_thread_task_runner.h"
tfarina@chromium.orge2903a52013-03-17 14:52:05 +090019#include "base/stl_util.h"
skyostil97aefe12015-05-01 04:06:15 +090020#include "base/thread_task_runner_handle.h"
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +090021#include "base/threading/platform_thread.h"
mbelshe@google.com877d2032008-10-23 08:09:21 +090022
23///////////////////////////////////////////////////////////////////////////////
24//
25// OVERVIEW:
26//
27// A thread-safe container for a list of observers.
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090028// This is similar to the observer_list (see observer_list.h), but it
mbelshe@google.com877d2032008-10-23 08:09:21 +090029// is more robust for multi-threaded situations.
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090030//
mbelshe@google.com877d2032008-10-23 08:09:21 +090031// 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.
pkasting@chromium.orgaed4e582010-06-26 06:30:38 +090035// * Any thread may trigger a notification via Notify().
mbelshe@google.com877d2032008-10-23 08:09:21 +090036// * Observers can remove themselves from the observer list inside
37// of a callback.
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.
41//
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.
47//
48// IMPLEMENTATION NOTES
49// The ObserverListThreadSafe maintains an ObserverList for each thread
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090050// which uses the ThreadSafeObserver. When Notifying the observers,
mbelshe@google.com877d2032008-10-23 08:09:21 +090051// we simply call PostTask to each registered thread, and then each thread
52// will notify its regular ObserverList.
53//
54///////////////////////////////////////////////////////////////////////////////
akalin@chromium.orge43be3d2011-01-12 06:19:54 +090055
brettwcf584602015-06-02 14:34:43 +090056namespace base {
57
akalin@chromium.orge43be3d2011-01-12 06:19:54 +090058// Forward declaration for ObserverListThreadSafeTraits.
59template <class ObserverType>
60class ObserverListThreadSafe;
61
brettwcf584602015-06-02 14:34:43 +090062namespace internal {
63
jhawkins@chromium.org4a310212012-01-04 04:36:57 +090064// An UnboundMethod is a wrapper for a method where the actual object is
65// provided at Run dispatch time.
66template <class T, class Method, class Params>
67class UnboundMethod {
68 public:
69 UnboundMethod(Method m, const Params& p) : m_(m), p_(p) {
70 COMPILE_ASSERT(
brettwcf584602015-06-02 14:34:43 +090071 (internal::ParamsUseScopedRefptrCorrectly<Params>::value),
jhawkins@chromium.org4a310212012-01-04 04:36:57 +090072 badunboundmethodparams);
73 }
74 void Run(T* obj) const {
75 DispatchToMethod(obj, m_, p_);
76 }
77 private:
78 Method m_;
79 Params p_;
80};
81
brettwcf584602015-06-02 14:34:43 +090082} // namespace internal
83
akalin@chromium.orge43be3d2011-01-12 06:19:54 +090084// This class is used to work around VS2005 not accepting:
85//
86// friend class
brettwcf584602015-06-02 14:34:43 +090087// base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType>>;
akalin@chromium.orge43be3d2011-01-12 06:19:54 +090088//
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.
93template <class T>
94struct ObserverListThreadSafeTraits {
95 static void Destruct(const ObserverListThreadSafe<T>* x) {
96 delete x;
97 }
98};
99
mbelshe@google.com877d2032008-10-23 08:09:21 +0900100template <class ObserverType>
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +0900101class ObserverListThreadSafe
brettwcf584602015-06-02 14:34:43 +0900102 : public RefCountedThreadSafe<
akalin@chromium.orge43be3d2011-01-12 06:19:54 +0900103 ObserverListThreadSafe<ObserverType>,
brettwcf584602015-06-02 14:34:43 +0900104 ObserverListThreadSafeTraits<ObserverType>> {
mbelshe@google.com877d2032008-10-23 08:09:21 +0900105 public:
willchan@chromium.org4c7f03e2010-09-01 07:54:21 +0900106 typedef typename ObserverList<ObserverType>::NotificationType
107 NotificationType;
108
109 ObserverListThreadSafe()
110 : type_(ObserverListBase<ObserverType>::NOTIFY_ALL) {}
111 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {}
mbelshe@google.com877d2032008-10-23 08:09:21 +0900112
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900113 // Add an observer to the list. An observer should not be added to
114 // the same list more than once.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900115 void AddObserver(ObserverType* obs) {
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900116 // If there is not a current MessageLoop, it is impossible to notify on it,
117 // so do not add the observer.
brettwcf584602015-06-02 14:34:43 +0900118 if (!MessageLoop::current())
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900119 return;
120
robliao3c02ea22015-04-24 07:45:32 +0900121 ObserverList<ObserverType>* list = nullptr;
brettwcf584602015-06-02 14:34:43 +0900122 PlatformThreadId thread_id = PlatformThread::CurrentId();
mbelshe@google.com877d2032008-10-23 08:09:21 +0900123 {
brettwcf584602015-06-02 14:34:43 +0900124 AutoLock lock(list_lock_);
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900125 if (observer_lists_.find(thread_id) == observer_lists_.end())
126 observer_lists_[thread_id] = new ObserverListContext(type_);
127 list = &(observer_lists_[thread_id]->list);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900128 }
129 list->AddObserver(obs);
130 }
131
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900132 // Remove an observer from the list if it is in the list.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900133 // If there are pending notifications in-transit to the observer, they will
134 // be aborted.
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900135 // If the observer to be removed is in the list, RemoveObserver MUST
136 // be called from the same thread which called AddObserver.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900137 void RemoveObserver(ObserverType* obs) {
robliao3c02ea22015-04-24 07:45:32 +0900138 ObserverListContext* context = nullptr;
139 ObserverList<ObserverType>* list = nullptr;
brettwcf584602015-06-02 14:34:43 +0900140 PlatformThreadId thread_id = PlatformThread::CurrentId();
mbelshe@google.com877d2032008-10-23 08:09:21 +0900141 {
brettwcf584602015-06-02 14:34:43 +0900142 AutoLock lock(list_lock_);
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900143 typename ObserversListMap::iterator it = observer_lists_.find(thread_id);
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900144 if (it == observer_lists_.end()) {
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900145 // This will happen if we try to remove an observer on a thread
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900146 // we never added an observer for.
mbelshe@google.com2d95cab2008-11-04 02:15:07 +0900147 return;
148 }
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900149 context = it->second;
150 list = &context->list;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900151
152 // If we're about to remove the last observer from the list,
153 // then we can remove this observer_list entirely.
akalin@chromium.orgcbec5fb2011-06-05 16:07:12 +0900154 if (list->HasObserver(obs) && list->size() == 1)
155 observer_lists_.erase(it);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900156 }
157 list->RemoveObserver(obs);
158
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)
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900163 delete context;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900164 }
165
sergeyu@chromium.org86992ef2012-02-08 09:22:11 +0900166 // Verifies that the list is currently empty (i.e. there are no observers).
167 void AssertEmpty() const {
brettwcf584602015-06-02 14:34:43 +0900168 AutoLock lock(list_lock_);
sergeyu@chromium.org86992ef2012-02-08 09:22:11 +0900169 DCHECK(observer_lists_.empty());
170 }
171
mbelshe@google.com877d2032008-10-23 08:09:21 +0900172 // Notify methods.
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.
thakisd5c85872014-12-23 11:02:57 +0900177 template <class Method, class... Params>
reillyg57b1bc52015-02-10 05:18:33 +0900178 void Notify(const tracked_objects::Location& from_here,
179 Method m,
180 const Params&... params) {
brettwcf584602015-06-02 14:34:43 +0900181 internal::UnboundMethod<ObserverType, Method, Tuple<Params...>> method(
182 m, MakeTuple(params...));
mbelshe@google.com877d2032008-10-23 08:09:21 +0900183
brettwcf584602015-06-02 14:34:43 +0900184 AutoLock lock(list_lock_);
thakisd5c85872014-12-23 11:02:57 +0900185 for (const auto& entry : observer_lists_) {
186 ObserverListContext* context = entry.second;
skyostil97aefe12015-05-01 04:06:15 +0900187 context->task_runner->PostTask(
reillyg57b1bc52015-02-10 05:18:33 +0900188 from_here,
brettwcf584602015-06-02 14:34:43 +0900189 Bind(&ObserverListThreadSafe<ObserverType>::template NotifyWrapper<
190 Method, Tuple<Params...>>,
thakisd5c85872014-12-23 11:02:57 +0900191 this, context, method));
192 }
mbelshe@google.com877d2032008-10-23 08:09:21 +0900193 }
194
mbelshe@google.com877d2032008-10-23 08:09:21 +0900195 private:
akalin@chromium.orge43be3d2011-01-12 06:19:54 +0900196 // See comment above ObserverListThreadSafeTraits' definition.
197 friend struct ObserverListThreadSafeTraits<ObserverType>;
198
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900199 struct ObserverListContext {
200 explicit ObserverListContext(NotificationType type)
brettwcf584602015-06-02 14:34:43 +0900201 : task_runner(ThreadTaskRunnerHandle::Get()), list(type) {}
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900202
brettwcf584602015-06-02 14:34:43 +0900203 scoped_refptr<SingleThreadTaskRunner> task_runner;
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900204 ObserverList<ObserverType> list;
205
danakjde6142a2015-03-08 08:04:23 +0900206 private:
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900207 DISALLOW_COPY_AND_ASSIGN(ObserverListContext);
208 };
209
akalin@chromium.org982d9d52011-01-11 05:40:36 +0900210 ~ObserverListThreadSafe() {
tfarina@chromium.orge2903a52013-03-17 14:52:05 +0900211 STLDeleteValues(&observer_lists_);
akalin@chromium.org982d9d52011-01-11 05:40:36 +0900212 }
213
mbelshe@google.com877d2032008-10-23 08:09:21 +0900214 // 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>
brettwcf584602015-06-02 14:34:43 +0900218 void NotifyWrapper(
219 ObserverListContext* context,
220 const internal::UnboundMethod<ObserverType, Method, Params>& method) {
mbelshe@google.com877d2032008-10-23 08:09:21 +0900221 // Check that this list still needs notifications.
222 {
brettwcf584602015-06-02 14:34:43 +0900223 AutoLock lock(list_lock_);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900224 typename ObserversListMap::iterator it =
brettwcf584602015-06-02 14:34:43 +0900225 observer_lists_.find(PlatformThread::CurrentId());
mbelshe@google.com877d2032008-10-23 08:09:21 +0900226
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
230 // notification.
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900231 if (it == observer_lists_.end() || it->second != context)
mbelshe@google.com877d2032008-10-23 08:09:21 +0900232 return;
233 }
234
235 {
danakj10235892015-03-10 02:45:39 +0900236 typename ObserverList<ObserverType>::Iterator it(&context->list);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900237 ObserverType* obs;
robliao3c02ea22015-04-24 07:45:32 +0900238 while ((obs = it.GetNext()) != nullptr)
mbelshe@google.com877d2032008-10-23 08:09:21 +0900239 method.Run(obs);
240 }
241
242 // If there are no more observers on the list, we can now delete it.
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900243 if (context->list.size() == 0) {
mbelshe@google.com877d2032008-10-23 08:09:21 +0900244 {
brettwcf584602015-06-02 14:34:43 +0900245 AutoLock lock(list_lock_);
willchan@chromium.org2777ca52010-09-18 04:33:06 +0900246 // 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.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900249 typename ObserversListMap::iterator it =
brettwcf584602015-06-02 14:34:43 +0900250 observer_lists_.find(PlatformThread::CurrentId());
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900251 if (it != observer_lists_.end() && it->second == context)
willchan@chromium.org2777ca52010-09-18 04:33:06 +0900252 observer_lists_.erase(it);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900253 }
adamk@chromium.org2bc73e72011-08-10 06:29:59 +0900254 delete context;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900255 }
256 }
257
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900258 // 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.
brettwcf584602015-06-02 14:34:43 +0900261 typedef std::map<PlatformThreadId, ObserverListContext*>
rsesek@chromium.org1aab77c2011-11-24 05:34:04 +0900262 ObserversListMap;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900263
brettwcf584602015-06-02 14:34:43 +0900264 mutable Lock list_lock_; // Protects the observer_lists_.
mbelshe@google.com877d2032008-10-23 08:09:21 +0900265 ObserversListMap observer_lists_;
willchan@chromium.org4c7f03e2010-09-01 07:54:21 +0900266 const NotificationType type_;
mbelshe@google.com877d2032008-10-23 08:09:21 +0900267
tfarina@chromium.org0aad8422010-06-05 01:13:51 +0900268 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe);
mbelshe@google.com877d2032008-10-23 08:09:21 +0900269};
270
brettwcf584602015-06-02 14:34:43 +0900271} // namespace base
272
mbelshe@google.com877d2032008-10-23 08:09:21 +0900273#endif // BASE_OBSERVER_LIST_THREADSAFE_H_