Updating trunk VERSION from 833.0 to 834.0
[chromium-blink-merge.git] / base / observer_list_threadsafe.h
blobf4ff68d7c942513dddcb79f2c26bd90549eeab5e
1 // Copyright (c) 2011 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_
7 #pragma once
9 #include <algorithm>
10 #include <map>
12 #include "base/basictypes.h"
13 #include "base/callback_old.h"
14 #include "base/logging.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/message_loop.h"
17 #include "base/observer_list.h"
18 #include "base/task.h"
20 ///////////////////////////////////////////////////////////////////////////////
22 // OVERVIEW:
24 // A thread-safe container for a list of observers.
25 // This is similar to the observer_list (see observer_list.h), but it
26 // is more robust for multi-threaded situations.
28 // The following use cases are supported:
29 // * Observers can register for notifications from any thread.
30 // Callbacks to the observer will occur on the same thread where
31 // the observer initially called AddObserver() from.
32 // * Any thread may trigger a notification via Notify().
33 // * Observers can remove themselves from the observer list inside
34 // of a callback.
35 // * If one thread is notifying observers concurrently with an observer
36 // removing itself from the observer list, the notifications will
37 // be silently dropped.
39 // The drawback of the threadsafe observer list is that notifications
40 // are not as real-time as the non-threadsafe version of this class.
41 // Notifications will always be done via PostTask() to another thread,
42 // whereas with the non-thread-safe observer_list, notifications happen
43 // synchronously and immediately.
45 // IMPLEMENTATION NOTES
46 // The ObserverListThreadSafe maintains an ObserverList for each thread
47 // which uses the ThreadSafeObserver. When Notifying the observers,
48 // we simply call PostTask to each registered thread, and then each thread
49 // will notify its regular ObserverList.
51 ///////////////////////////////////////////////////////////////////////////////
53 // Forward declaration for ObserverListThreadSafeTraits.
54 template <class ObserverType>
55 class ObserverListThreadSafe;
57 // This class is used to work around VS2005 not accepting:
59 // friend class
60 // base::RefCountedThreadSafe<ObserverListThreadSafe<ObserverType> >;
62 // Instead of friending the class, we could friend the actual function
63 // which calls delete. However, this ends up being
64 // RefCountedThreadSafe::DeleteInternal(), which is private. So we
65 // define our own templated traits class so we can friend it.
66 template <class T>
67 struct ObserverListThreadSafeTraits {
68 static void Destruct(const ObserverListThreadSafe<T>* x) {
69 delete x;
73 template <class ObserverType>
74 class ObserverListThreadSafe
75 : public base::RefCountedThreadSafe<
76 ObserverListThreadSafe<ObserverType>,
77 ObserverListThreadSafeTraits<ObserverType> > {
78 public:
79 typedef typename ObserverList<ObserverType>::NotificationType
80 NotificationType;
82 ObserverListThreadSafe()
83 : type_(ObserverListBase<ObserverType>::NOTIFY_ALL) {}
84 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {}
86 // Add an observer to the list. An observer should not be added to
87 // the same list more than once.
88 void AddObserver(ObserverType* obs) {
89 ObserverList<ObserverType>* list = NULL;
90 MessageLoop* loop = MessageLoop::current();
91 // TODO(mbelshe): Get rid of this check. Its needed right now because
92 // Time currently triggers usage of the ObserverList.
93 // And unittests use time without a MessageLoop.
94 if (!loop)
95 return; // Some unittests may access this without a message loop.
97 base::AutoLock lock(list_lock_);
98 if (observer_lists_.find(loop) == observer_lists_.end())
99 observer_lists_[loop] = new ObserverList<ObserverType>(type_);
100 list = observer_lists_[loop];
102 list->AddObserver(obs);
105 // Remove an observer from the list if it is in the list.
106 // If there are pending notifications in-transit to the observer, they will
107 // be aborted.
108 // If the observer to be removed is in the list, RemoveObserver MUST
109 // be called from the same thread which called AddObserver.
110 void RemoveObserver(ObserverType* obs) {
111 ObserverList<ObserverType>* list = NULL;
112 MessageLoop* loop = MessageLoop::current();
113 if (!loop)
114 return; // On shutdown, it is possible that current() is already null.
116 base::AutoLock lock(list_lock_);
117 typename ObserversListMap::iterator it = observer_lists_.find(loop);
118 if (it == observer_lists_.end()) {
119 // This may happen if we try to remove an observer on a thread
120 // we never added an observer for.
121 return;
123 list = it->second;
125 // If we're about to remove the last observer from the list,
126 // then we can remove this observer_list entirely.
127 if (list->HasObserver(obs) && list->size() == 1)
128 observer_lists_.erase(it);
130 list->RemoveObserver(obs);
132 // If RemoveObserver is called from a notification, the size will be
133 // nonzero. Instead of deleting here, the NotifyWrapper will delete
134 // when it finishes iterating.
135 if (list->size() == 0)
136 delete list;
139 // Notify methods.
140 // Make a thread-safe callback to each Observer in the list.
141 // Note, these calls are effectively asynchronous. You cannot assume
142 // that at the completion of the Notify call that all Observers have
143 // been Notified. The notification may still be pending delivery.
144 template <class Method>
145 void Notify(Method m) {
146 UnboundMethod<ObserverType, Method, Tuple0> method(m, MakeTuple());
147 Notify<Method, Tuple0>(method);
150 template <class Method, class A>
151 void Notify(Method m, const A& a) {
152 UnboundMethod<ObserverType, Method, Tuple1<A> > method(m, MakeTuple(a));
153 Notify<Method, Tuple1<A> >(method);
156 template <class Method, class A, class B>
157 void Notify(Method m, const A& a, const B& b) {
158 UnboundMethod<ObserverType, Method, Tuple2<A, B> > method(
159 m, MakeTuple(a, b));
160 Notify<Method, Tuple2<A, B> >(method);
163 template <class Method, class A, class B, class C>
164 void Notify(Method m, const A& a, const B& b, const C& c) {
165 UnboundMethod<ObserverType, Method, Tuple3<A, B, C> > method(
166 m, MakeTuple(a, b, c));
167 Notify<Method, Tuple3<A, B, C> >(method);
170 template <class Method, class A, class B, class C, class D>
171 void Notify(Method m, const A& a, const B& b, const C& c, const D& d) {
172 UnboundMethod<ObserverType, Method, Tuple4<A, B, C, D> > method(
173 m, MakeTuple(a, b, c, d));
174 Notify<Method, Tuple4<A, B, C, D> >(method);
177 // TODO(mbelshe): Add more wrappers for Notify() with more arguments.
179 private:
180 // See comment above ObserverListThreadSafeTraits' definition.
181 friend struct ObserverListThreadSafeTraits<ObserverType>;
183 ~ObserverListThreadSafe() {
184 typename ObserversListMap::const_iterator it;
185 for (it = observer_lists_.begin(); it != observer_lists_.end(); ++it)
186 delete (*it).second;
187 observer_lists_.clear();
190 template <class Method, class Params>
191 void Notify(const UnboundMethod<ObserverType, Method, Params>& method) {
192 base::AutoLock lock(list_lock_);
193 typename ObserversListMap::iterator it;
194 for (it = observer_lists_.begin(); it != observer_lists_.end(); ++it) {
195 MessageLoop* loop = (*it).first;
196 ObserverList<ObserverType>* list = (*it).second;
197 loop->PostTask(
198 FROM_HERE,
199 NewRunnableMethod(this,
200 &ObserverListThreadSafe<ObserverType>::
201 template NotifyWrapper<Method, Params>, list, method));
205 // Wrapper which is called to fire the notifications for each thread's
206 // ObserverList. This function MUST be called on the thread which owns
207 // the unsafe ObserverList.
208 template <class Method, class Params>
209 void NotifyWrapper(ObserverList<ObserverType>* list,
210 const UnboundMethod<ObserverType, Method, Params>& method) {
212 // Check that this list still needs notifications.
214 base::AutoLock lock(list_lock_);
215 typename ObserversListMap::iterator it =
216 observer_lists_.find(MessageLoop::current());
218 // The ObserverList could have been removed already. In fact, it could
219 // have been removed and then re-added! If the master list's loop
220 // does not match this one, then we do not need to finish this
221 // notification.
222 if (it == observer_lists_.end() || it->second != list)
223 return;
227 typename ObserverList<ObserverType>::Iterator it(*list);
228 ObserverType* obs;
229 while ((obs = it.GetNext()) != NULL)
230 method.Run(obs);
233 // If there are no more observers on the list, we can now delete it.
234 if (list->size() == 0) {
236 base::AutoLock lock(list_lock_);
237 // Remove |list| if it's not already removed.
238 // This can happen if multiple observers got removed in a notification.
239 // See http://crbug.com/55725.
240 typename ObserversListMap::iterator it =
241 observer_lists_.find(MessageLoop::current());
242 if (it != observer_lists_.end() && it->second == list)
243 observer_lists_.erase(it);
245 delete list;
249 typedef std::map<MessageLoop*, ObserverList<ObserverType>*> ObserversListMap;
251 // These are marked mutable to facilitate having NotifyAll be const.
252 base::Lock list_lock_; // Protects the observer_lists_.
253 ObserversListMap observer_lists_;
254 const NotificationType type_;
256 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe);
259 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_