Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(468)

Side by Side Diff: base/observer_list_threadsafe.h

Issue 2805933002: [reland] Allow ObserverListThreadSafe to be used from sequenced tasks. (Closed)
Patch Set: CR-gab Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | base/observer_list_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #ifndef BASE_OBSERVER_LIST_THREADSAFE_H_ 5 #ifndef BASE_OBSERVER_LIST_THREADSAFE_H_
6 #define BASE_OBSERVER_LIST_THREADSAFE_H_ 6 #define BASE_OBSERVER_LIST_THREADSAFE_H_
7 7
8 #include <algorithm> 8 #include <unordered_map>
9 #include <map>
10 #include <memory>
11 #include <tuple>
12 9
13 #include "base/bind.h" 10 #include "base/bind.h"
14 #include "base/location.h" 11 #include "base/location.h"
15 #include "base/logging.h" 12 #include "base/logging.h"
16 #include "base/macros.h" 13 #include "base/macros.h"
17 #include "base/memory/ptr_util.h"
18 #include "base/memory/ref_counted.h" 14 #include "base/memory/ref_counted.h"
19 #include "base/observer_list.h" 15 #include "base/observer_list.h"
16 #include "base/sequenced_task_runner.h"
17 #include "base/stl_util.h"
18 #include "base/synchronization/lock.h"
19 #include "base/threading/sequenced_task_runner_handle.h"
20 #include "base/threading/thread_local.h"
21 #include "build/build_config.h"
22
23 // TODO(fdoray): Removing these includes causes IWYU failures in other headers,
24 // remove them in a follow- up CL.
25 #include "base/memory/ptr_util.h"
20 #include "base/single_thread_task_runner.h" 26 #include "base/single_thread_task_runner.h"
21 #include "base/threading/platform_thread.h"
22 #include "base/threading/thread_task_runner_handle.h" 27 #include "base/threading/thread_task_runner_handle.h"
23 28
24 /////////////////////////////////////////////////////////////////////////////// 29 ///////////////////////////////////////////////////////////////////////////////
25 // 30 //
26 // OVERVIEW: 31 // OVERVIEW:
27 // 32 //
28 // A thread-safe container for a list of observers. 33 // A thread-safe container for a list of observers. This is similar to the
29 // This is similar to the observer_list (see observer_list.h), but it 34 // observer_list (see observer_list.h), but it is more robust for multi-
30 // is more robust for multi-threaded situations. 35 // threaded situations.
31 // 36 //
32 // The following use cases are supported: 37 // The following use cases are supported:
33 // * Observers can register for notifications from any thread. 38 // * Observers can register for notifications from any sequence. They are
34 // Callbacks to the observer will occur on the same thread where 39 // always notified on the sequence from which they were registered.
35 // the observer initially called AddObserver() from. 40 // * Any sequence may trigger a notification via Notify().
36 // * Any thread may trigger a notification via Notify(). 41 // * Observers can remove themselves from the observer list inside of a
37 // * Observers can remove themselves from the observer list inside 42 // callback.
38 // of a callback. 43 // * If one sequence is notifying observers concurrently with an observer
39 // * If one thread is notifying observers concurrently with an observer 44 // removing itself from the observer list, the notifications will be
40 // removing itself from the observer list, the notifications will 45 // silently dropped.
41 // be silently dropped.
42 // 46 //
43 // The drawback of the threadsafe observer list is that notifications 47 // The drawback of the threadsafe observer list is that notifications are not
44 // are not as real-time as the non-threadsafe version of this class. 48 // as real-time as the non-threadsafe version of this class. Notifications
45 // Notifications will always be done via PostTask() to another thread, 49 // will always be done via PostTask() to another sequence, whereas with the
46 // whereas with the non-thread-safe observer_list, notifications happen 50 // non-thread-safe observer_list, notifications happen synchronously.
47 // synchronously and immediately.
48 //
49 // IMPLEMENTATION NOTES
50 // The ObserverListThreadSafe maintains an ObserverList for each thread
51 // which uses the ThreadSafeObserver. When Notifying the observers,
52 // we simply call PostTask to each registered thread, and then each thread
53 // will notify its regular ObserverList.
54 // 51 //
55 /////////////////////////////////////////////////////////////////////////////// 52 ///////////////////////////////////////////////////////////////////////////////
56 53
57 namespace base { 54 namespace base {
58 namespace internal { 55 namespace internal {
59 56
60 template <typename ObserverType, typename Method> 57 template <typename ObserverType, typename Method>
61 struct Dispatcher; 58 struct Dispatcher;
62 59
63 template <typename ObserverType, typename ReceiverType, typename... Params> 60 template <typename ObserverType, typename ReceiverType, typename... Params>
64 struct Dispatcher<ObserverType, void(ReceiverType::*)(Params...)> { 61 struct Dispatcher<ObserverType, void(ReceiverType::*)(Params...)> {
65 static void Run(void(ReceiverType::* m)(Params...), 62 static void Run(void(ReceiverType::* m)(Params...),
66 Params... params, ObserverType* obj) { 63 Params... params, ObserverType* obj) {
67 (obj->*m)(std::forward<Params>(params)...); 64 (obj->*m)(std::forward<Params>(params)...);
68 } 65 }
69 }; 66 };
70 67
71 } // namespace internal 68 } // namespace internal
72 69
73 template <class ObserverType> 70 template <class ObserverType>
74 class ObserverListThreadSafe 71 class ObserverListThreadSafe
75 : public RefCountedThreadSafe<ObserverListThreadSafe<ObserverType>> { 72 : public RefCountedThreadSafe<ObserverListThreadSafe<ObserverType>> {
76 public: 73 public:
77 using NotificationType = 74 using NotificationType =
78 typename ObserverList<ObserverType>::NotificationType; 75 typename ObserverList<ObserverType>::NotificationType;
79 76
80 ObserverListThreadSafe() 77 ObserverListThreadSafe() = default;
81 : type_(ObserverListBase<ObserverType>::NOTIFY_ALL) {}
82 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {} 78 explicit ObserverListThreadSafe(NotificationType type) : type_(type) {}
83 79
84 // Add an observer to the list. An observer should not be added to 80 // Adds |observer| to the list. |observer| must not already be in the list.
85 // the same list more than once. 81 void AddObserver(ObserverType* observer) {
86 void AddObserver(ObserverType* obs) { 82 // TODO(fdoray): Change this to a DCHECK once all call sites have a
87 // If there is no ThreadTaskRunnerHandle, it is impossible to notify on it, 83 // SequencedTaskRunnerHandle.
88 // so do not add the observer. 84 if (!SequencedTaskRunnerHandle::IsSet())
89 if (!ThreadTaskRunnerHandle::IsSet())
90 return; 85 return;
91 86
92 ObserverList<ObserverType>* list = nullptr; 87 AutoLock auto_lock(lock_);
93 PlatformThreadId thread_id = PlatformThread::CurrentId(); 88
94 { 89 // Add |observer| to the list of observers.
95 AutoLock lock(list_lock_); 90 DCHECK(!ContainsKey(observers_, observer));
96 if (observer_lists_.find(thread_id) == observer_lists_.end()) { 91 const scoped_refptr<SequencedTaskRunner> task_runner =
97 observer_lists_[thread_id] = 92 SequencedTaskRunnerHandle::Get();
98 base::MakeUnique<ObserverListContext>(type_); 93 observers_[observer] = task_runner;
94
95 // If this is called while a notification is being dispatched on this thread
96 // and |type_| is NOTIFY_ALL, |observer| must be notified (if a notification
97 // is being dispatched on another thread in parallel, the notification may
98 // or may not make it to |observer| depending on the outcome of the race to
99 // |lock_|).
100 if (type_ == NotificationType::NOTIFY_ALL) {
101 const NotificationData* current_notification =
102 tls_current_notification_.Get();
103 if (current_notification) {
104 task_runner->PostTask(
105 current_notification->from_here,
106 Bind(&ObserverListThreadSafe<ObserverType>::NotifyWrapper, this,
107 observer, *current_notification));
99 } 108 }
100 list = &(observer_lists_[thread_id]->list);
101 } 109 }
102 list->AddObserver(obs);
103 } 110 }
104 111
105 // Remove an observer from the list if it is in the list. 112 // 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 113 //
107 // be aborted. 114 // If a notification was sent to the observer but hasn't started to run yet,
108 // If the observer to be removed is in the list, RemoveObserver MUST 115 // it will be aborted. If a notification has started to run, removing the
109 // be called from the same thread which called AddObserver. 116 // observer won't stop it.
110 void RemoveObserver(ObserverType* obs) { 117 void RemoveObserver(ObserverType* observer) {
111 PlatformThreadId thread_id = PlatformThread::CurrentId(); 118 AutoLock auto_lock(lock_);
112 { 119 observers_.erase(observer);
113 AutoLock lock(list_lock_);
114 auto it = observer_lists_.find(thread_id);
115 if (it == observer_lists_.end()) {
116 // This will happen if we try to remove an observer on a thread
117 // we never added an observer for.
118 return;
119 }
120 ObserverList<ObserverType>& list = it->second->list;
121
122 list.RemoveObserver(obs);
123
124 // If that was the last observer in the list, remove the ObserverList
125 // entirely.
126 if (list.size() == 0)
127 observer_lists_.erase(it);
128 }
129 } 120 }
130 121
131 // Verifies that the list is currently empty (i.e. there are no observers). 122 // Verifies that the list is currently empty (i.e. there are no observers).
132 void AssertEmpty() const { 123 void AssertEmpty() const {
133 AutoLock lock(list_lock_); 124 #if DCHECK_IS_ON()
134 DCHECK(observer_lists_.empty()); 125 AutoLock auto_lock(lock_);
126 DCHECK(observers_.empty());
127 #endif
135 } 128 }
136 129
137 // Notify methods. 130 // Asynchronously invokes a callback on all observers, on their registration
138 // Make a thread-safe callback to each Observer in the list. 131 // sequence. You cannot assume that at the completion of the Notify call that
139 // Note, these calls are effectively asynchronous. You cannot assume 132 // all Observers have been Notified. The notification may still be pending
140 // that at the completion of the Notify call that all Observers have 133 // delivery.
141 // been Notified. The notification may still be pending delivery.
142 template <typename Method, typename... Params> 134 template <typename Method, typename... Params>
143 void Notify(const tracked_objects::Location& from_here, 135 void Notify(const tracked_objects::Location& from_here,
144 Method m, Params&&... params) { 136 Method m, Params&&... params) {
145 Callback<void(ObserverType*)> method = 137 Callback<void(ObserverType*)> method =
146 Bind(&internal::Dispatcher<ObserverType, Method>::Run, 138 Bind(&internal::Dispatcher<ObserverType, Method>::Run,
147 m, std::forward<Params>(params)...); 139 m, std::forward<Params>(params)...);
148 140
149 AutoLock lock(list_lock_); 141 AutoLock lock(lock_);
150 for (const auto& entry : observer_lists_) { 142 for (const auto& observer : observers_) {
151 ObserverListContext* context = entry.second.get(); 143 observer.second->PostTask(
152 context->task_runner->PostTask(
153 from_here, 144 from_here,
154 Bind(&ObserverListThreadSafe<ObserverType>::NotifyWrapper, 145 Bind(&ObserverListThreadSafe<ObserverType>::NotifyWrapper, this,
155 this, context, method)); 146 observer.first, NotificationData(from_here, method)));
156 } 147 }
157 } 148 }
158 149
159 private: 150 private:
160 friend class RefCountedThreadSafe<ObserverListThreadSafe<ObserverType>>; 151 friend class RefCountedThreadSafe<ObserverListThreadSafe<ObserverType>>;
161 152
162 struct ObserverListContext { 153 struct NotificationData {
163 explicit ObserverListContext(NotificationType type) 154 NotificationData(const tracked_objects::Location& from_here_in,
164 : task_runner(ThreadTaskRunnerHandle::Get()), list(type) {} 155 const Callback<void(ObserverType*)>& method_in)
156 : from_here(from_here_in), method(method_in) {}
165 157
166 scoped_refptr<SingleThreadTaskRunner> task_runner; 158 tracked_objects::Location from_here;
167 ObserverList<ObserverType> list; 159 Callback<void(ObserverType*)> method;
168
169 private:
170 DISALLOW_COPY_AND_ASSIGN(ObserverListContext);
171 }; 160 };
172 161
173 ~ObserverListThreadSafe() { 162 ~ObserverListThreadSafe() = default;
163
164 void NotifyWrapper(ObserverType* observer,
165 const NotificationData& notification) {
166 {
167 AutoLock auto_lock(lock_);
168
169 // Check whether the observer still needs a notification.
170 auto it = observers_.find(observer);
171 if (it == observers_.end())
172 return;
173 DCHECK(it->second->RunsTasksOnCurrentThread());
174 }
175
176 // Keep track of the notification being dispatched on the current thread.
177 // This will be used if the callback below calls AddObserver().
178 //
179 // Note: |tls_current_notification_| may not be nullptr if this runs in a
180 // nested loop started by a notification callback. In that case, it is
181 // important to save the previous value to restore it later.
182 const NotificationData* const previous_notification =
183 tls_current_notification_.Get();
184 tls_current_notification_.Set(&notification);
185
186 // Invoke the callback.
187 notification.method.Run(observer);
188
189 // Reset the notification being dispatched on the current thread to its
190 // previous value.
191 tls_current_notification_.Set(previous_notification);
174 } 192 }
175 193
176 // Wrapper which is called to fire the notifications for each thread's 194 const NotificationType type_ = NotificationType::NOTIFY_ALL;
177 // ObserverList. This function MUST be called on the thread which owns
178 // the unsafe ObserverList.
179 void NotifyWrapper(ObserverListContext* context,
180 const Callback<void(ObserverType*)>& method) {
181 // Check that this list still needs notifications.
182 {
183 AutoLock lock(list_lock_);
184 auto it = observer_lists_.find(PlatformThread::CurrentId());
185 195
186 // The ObserverList could have been removed already. In fact, it could 196 // Synchronizes access to |observers_|.
187 // have been removed and then re-added! If the master list's loop 197 mutable Lock lock_;
188 // does not match this one, then we do not need to finish this
189 // notification.
190 if (it == observer_lists_.end() || it->second.get() != context)
191 return;
192 }
193 198
194 for (auto& observer : context->list) { 199 // Keys are observers. Values are the SequencedTaskRunners on which they must
195 method.Run(&observer); 200 // be notified.
196 } 201 std::unordered_map<ObserverType*, scoped_refptr<SequencedTaskRunner>>
202 observers_;
197 203
198 // If there are no more observers on the list, we can now delete it. 204 // Notification being dispatched on the current thread.
199 if (context->list.size() == 0) { 205 ThreadLocalPointer<const NotificationData> tls_current_notification_;
200 {
201 AutoLock lock(list_lock_);
202 // Remove |list| if it's not already removed.
203 // This can happen if multiple observers got removed in a notification.
204 // See http://crbug.com/55725.
205 auto it = observer_lists_.find(PlatformThread::CurrentId());
206 if (it != observer_lists_.end() && it->second.get() == context)
207 observer_lists_.erase(it);
208 }
209 }
210 }
211
212 mutable Lock list_lock_; // Protects the observer_lists_.
213
214 // Key by PlatformThreadId because in tests, clients can attempt to remove
215 // observers without a SingleThreadTaskRunner. If this were keyed by
216 // SingleThreadTaskRunner, that operation would be silently ignored, leaving
217 // garbage in the ObserverList.
218 std::map<PlatformThreadId, std::unique_ptr<ObserverListContext>>
219 observer_lists_;
220
221 const NotificationType type_;
222 206
223 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe); 207 DISALLOW_COPY_AND_ASSIGN(ObserverListThreadSafe);
224 }; 208 };
225 209
226 } // namespace base 210 } // namespace base
227 211
228 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_ 212 #endif // BASE_OBSERVER_LIST_THREADSAFE_H_
OLDNEW
« no previous file with comments | « no previous file | base/observer_list_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698