blob: 1d4e04ac0d5bf35295bfcd8387b4fccc32e2cf9e [file] [log] [blame]
Trent Apted4d207362018-08-15 23:48:151// Copyright 2018 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.
4
5#include "base/observer_list_threadsafe.h"
6
7#include <memory>
8#include <vector>
9
10#include "base/bind.h"
11#include "base/compiler_specific.h"
12#include "base/location.h"
13#include "base/memory/weak_ptr.h"
Alexander Timin4f9c35c2018-11-01 20:15:2014#include "base/message_loop/message_loop.h"
Trent Apted4d207362018-08-15 23:48:1515#include "base/run_loop.h"
16#include "base/sequenced_task_runner.h"
17#include "base/single_thread_task_runner.h"
18#include "base/synchronization/waitable_event.h"
19#include "base/task/post_task.h"
20#include "base/task/task_scheduler/task_scheduler.h"
21#include "base/test/scoped_task_environment.h"
22#include "base/threading/platform_thread.h"
23#include "base/threading/thread_restrictions.h"
24#include "build/build_config.h"
25#include "testing/gtest/include/gtest/gtest.h"
26
27namespace base {
28namespace {
29
30constexpr int kThreadRunTime = 2000; // ms to run the multi-threaded test.
31
32class Foo {
33 public:
34 virtual void Observe(int x) = 0;
35 virtual ~Foo() = default;
36 virtual int GetValue() const { return 0; }
37};
38
39class Adder : public Foo {
40 public:
41 explicit Adder(int scaler) : total(0), scaler_(scaler) {}
42 ~Adder() override = default;
43
44 void Observe(int x) override { total += x * scaler_; }
45 int GetValue() const override { return total; }
46
47 int total;
48
49 private:
50 int scaler_;
51};
52
53class AddInObserve : public Foo {
54 public:
55 explicit AddInObserve(ObserverListThreadSafe<Foo>* observer_list)
56 : observer_list(observer_list), to_add_() {}
57
58 void SetToAdd(Foo* to_add) { to_add_ = to_add; }
59
60 void Observe(int x) override {
61 if (to_add_) {
62 observer_list->AddObserver(to_add_);
63 to_add_ = nullptr;
64 }
65 }
66
67 ObserverListThreadSafe<Foo>* observer_list;
68 Foo* to_add_;
69};
70
Sami Kyostila21f4d4c2018-11-29 11:11:3671// A task for use in the ThreadSafeObserver test which will add and remove
Trent Apted4d207362018-08-15 23:48:1572// itself from the notification list repeatedly.
Sami Kyostila21f4d4c2018-11-29 11:11:3673class AddRemoveThread : public Foo {
Trent Apted4d207362018-08-15 23:48:1574 public:
Sami Kyostila21f4d4c2018-11-29 11:11:3675 AddRemoveThread(ObserverListThreadSafe<Foo>* list, bool notify)
Trent Apted4d207362018-08-15 23:48:1576 : list_(list),
Sami Kyostila21f4d4c2018-11-29 11:11:3677 task_runner_(CreateSingleThreadTaskRunnerWithTraits(
78 TaskTraits(),
79 SingleThreadTaskRunnerThreadMode::DEDICATED)),
Trent Apted4d207362018-08-15 23:48:1580 in_list_(false),
81 start_(Time::Now()),
Trent Apted4d207362018-08-15 23:48:1582 do_notifies_(notify),
Sami Kyostila21f4d4c2018-11-29 11:11:3683 weak_factory_(this) {
84 task_runner_->PostTask(
Trent Apted4d207362018-08-15 23:48:1585 FROM_HERE,
86 base::BindOnce(&AddRemoveThread::AddTask, weak_factory_.GetWeakPtr()));
Trent Apted4d207362018-08-15 23:48:1587 }
88
Sami Kyostila21f4d4c2018-11-29 11:11:3689 ~AddRemoveThread() override = default;
90
Trent Apted4d207362018-08-15 23:48:1591 // This task just keeps posting to itself in an attempt to race with the
92 // notifier.
93 void AddTask() {
Trent Apted4d207362018-08-15 23:48:1594 if ((Time::Now() - start_).InMilliseconds() > kThreadRunTime) {
95 VLOG(1) << "DONE!";
96 return;
97 }
98
99 if (!in_list_) {
100 list_->AddObserver(this);
101 in_list_ = true;
102 }
103
104 if (do_notifies_) {
105 list_->Notify(FROM_HERE, &Foo::Observe, 10);
106 }
107
Sami Kyostila21f4d4c2018-11-29 11:11:36108 ThreadTaskRunnerHandle::Get()->PostTask(
Trent Apted4d207362018-08-15 23:48:15109 FROM_HERE,
110 base::BindOnce(&AddRemoveThread::AddTask, weak_factory_.GetWeakPtr()));
111 }
112
Trent Apted4d207362018-08-15 23:48:15113 void Observe(int x) override {
Trent Apted4d207362018-08-15 23:48:15114 // If we're getting called after we removed ourselves from the list, that is
115 // very bad!
Alexander Timind1e773cb2018-10-26 14:19:03116 EXPECT_TRUE(in_list_);
Trent Apted4d207362018-08-15 23:48:15117
118 // This callback should fire on the appropriate thread
Sami Kyostila21f4d4c2018-11-29 11:11:36119 EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
Trent Apted4d207362018-08-15 23:48:15120
121 list_->RemoveObserver(this);
122 in_list_ = false;
123 }
124
125 private:
126 ObserverListThreadSafe<Foo>* list_;
Sami Kyostila21f4d4c2018-11-29 11:11:36127 scoped_refptr<SingleThreadTaskRunner> task_runner_;
Trent Apted4d207362018-08-15 23:48:15128 bool in_list_; // Are we currently registered for notifications.
129 // in_list_ is only used on |this| thread.
130 Time start_; // The time we started the test.
131
Trent Apted4d207362018-08-15 23:48:15132 bool do_notifies_; // Whether these threads should do notifications.
Trent Apted4d207362018-08-15 23:48:15133
134 base::WeakPtrFactory<AddRemoveThread> weak_factory_;
135};
136
137} // namespace
138
139TEST(ObserverListThreadSafeTest, BasicTest) {
Sami Kyostila3f49cb572018-11-19 13:01:09140 test::ScopedTaskEnvironment scoped_task_environment;
Trent Apted4d207362018-08-15 23:48:15141
142 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
143 new ObserverListThreadSafe<Foo>);
144 Adder a(1);
145 Adder b(-1);
146 Adder c(1);
147 Adder d(-1);
148
149 observer_list->AddObserver(&a);
150 observer_list->AddObserver(&b);
151
152 observer_list->Notify(FROM_HERE, &Foo::Observe, 10);
153 RunLoop().RunUntilIdle();
154
155 observer_list->AddObserver(&c);
156 observer_list->AddObserver(&d);
157
158 observer_list->Notify(FROM_HERE, &Foo::Observe, 10);
159 observer_list->RemoveObserver(&c);
160 RunLoop().RunUntilIdle();
161
162 EXPECT_EQ(20, a.total);
163 EXPECT_EQ(-20, b.total);
164 EXPECT_EQ(0, c.total);
165 EXPECT_EQ(-10, d.total);
166}
167
168TEST(ObserverListThreadSafeTest, RemoveObserver) {
Sami Kyostila3f49cb572018-11-19 13:01:09169 test::ScopedTaskEnvironment scoped_task_environment;
Trent Apted4d207362018-08-15 23:48:15170
171 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
172 new ObserverListThreadSafe<Foo>);
173 Adder a(1), b(1);
174
175 // A workaround for the compiler bug. See http://crbug.com/121960.
176 EXPECT_NE(&a, &b);
177
178 // Should do nothing.
179 observer_list->RemoveObserver(&a);
180 observer_list->RemoveObserver(&b);
181
182 observer_list->Notify(FROM_HERE, &Foo::Observe, 10);
183 RunLoop().RunUntilIdle();
184
185 EXPECT_EQ(0, a.total);
186 EXPECT_EQ(0, b.total);
187
188 observer_list->AddObserver(&a);
189
190 // Should also do nothing.
191 observer_list->RemoveObserver(&b);
192
193 observer_list->Notify(FROM_HERE, &Foo::Observe, 10);
194 RunLoop().RunUntilIdle();
195
196 EXPECT_EQ(10, a.total);
197 EXPECT_EQ(0, b.total);
198}
199
200TEST(ObserverListThreadSafeTest, WithoutSequence) {
201 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
202 new ObserverListThreadSafe<Foo>);
203
204 Adder a(1), b(1), c(1);
205
206 // No sequence, so these should not be added.
207 observer_list->AddObserver(&a);
208 observer_list->AddObserver(&b);
209
210 {
211 // Add c when there's a sequence.
Sami Kyostila3f49cb572018-11-19 13:01:09212 test::ScopedTaskEnvironment scoped_task_environment;
Trent Apted4d207362018-08-15 23:48:15213 observer_list->AddObserver(&c);
214
215 observer_list->Notify(FROM_HERE, &Foo::Observe, 10);
216 RunLoop().RunUntilIdle();
217
218 EXPECT_EQ(0, a.total);
219 EXPECT_EQ(0, b.total);
220 EXPECT_EQ(10, c.total);
221
222 // Now add a when there's a sequence.
223 observer_list->AddObserver(&a);
224
225 // Remove c when there's a sequence.
226 observer_list->RemoveObserver(&c);
227
228 // Notify again.
229 observer_list->Notify(FROM_HERE, &Foo::Observe, 20);
230 RunLoop().RunUntilIdle();
231
232 EXPECT_EQ(20, a.total);
233 EXPECT_EQ(0, b.total);
234 EXPECT_EQ(10, c.total);
235 }
236
237 // Removing should always succeed with or without a sequence.
238 observer_list->RemoveObserver(&a);
239
240 // Notifying should not fail but should also be a no-op.
Sami Kyostila3f49cb572018-11-19 13:01:09241 test::ScopedTaskEnvironment scoped_task_environment;
Trent Apted4d207362018-08-15 23:48:15242 observer_list->AddObserver(&b);
243 observer_list->Notify(FROM_HERE, &Foo::Observe, 30);
244 RunLoop().RunUntilIdle();
245
246 EXPECT_EQ(20, a.total);
247 EXPECT_EQ(30, b.total);
248 EXPECT_EQ(10, c.total);
249}
250
251class FooRemover : public Foo {
252 public:
253 explicit FooRemover(ObserverListThreadSafe<Foo>* list) : list_(list) {}
254 ~FooRemover() override = default;
255
256 void AddFooToRemove(Foo* foo) { foos_.push_back(foo); }
257
258 void Observe(int x) override {
259 std::vector<Foo*> tmp;
260 tmp.swap(foos_);
jdoerrie6c6229352018-10-22 15:55:43261 for (auto* it : tmp) {
262 list_->RemoveObserver(it);
Trent Apted4d207362018-08-15 23:48:15263 }
264 }
265
266 private:
267 const scoped_refptr<ObserverListThreadSafe<Foo>> list_;
268 std::vector<Foo*> foos_;
269};
270
271TEST(ObserverListThreadSafeTest, RemoveMultipleObservers) {
Sami Kyostila3f49cb572018-11-19 13:01:09272 test::ScopedTaskEnvironment scoped_task_environment;
Trent Apted4d207362018-08-15 23:48:15273 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
274 new ObserverListThreadSafe<Foo>);
275
276 FooRemover a(observer_list.get());
277 Adder b(1);
278
279 observer_list->AddObserver(&a);
280 observer_list->AddObserver(&b);
281
282 a.AddFooToRemove(&a);
283 a.AddFooToRemove(&b);
284
285 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
286 RunLoop().RunUntilIdle();
287}
288
289// A test driver for a multi-threaded notification loop. Runs a number of
290// observer threads, each of which constantly adds/removes itself from the
291// observer list. Optionally, if cross_thread_notifies is set to true, the
292// observer threads will also trigger notifications to all observers.
293static void ThreadSafeObserverHarness(int num_threads,
294 bool cross_thread_notifies) {
Sami Kyostila3f49cb572018-11-19 13:01:09295 test::ScopedTaskEnvironment scoped_task_environment;
Trent Apted4d207362018-08-15 23:48:15296
297 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
298 new ObserverListThreadSafe<Foo>);
299 Adder a(1);
300 Adder b(-1);
301
302 observer_list->AddObserver(&a);
303 observer_list->AddObserver(&b);
304
Sami Kyostila21f4d4c2018-11-29 11:11:36305 std::vector<std::unique_ptr<AddRemoveThread>> threaded_observer;
Trent Apted4d207362018-08-15 23:48:15306 threaded_observer.reserve(num_threads);
Trent Apted4d207362018-08-15 23:48:15307 for (int index = 0; index < num_threads; index++) {
Sami Kyostila21f4d4c2018-11-29 11:11:36308 threaded_observer.push_back(std::make_unique<AddRemoveThread>(
309 observer_list.get(), cross_thread_notifies));
Trent Apted4d207362018-08-15 23:48:15310 }
311 ASSERT_EQ(static_cast<size_t>(num_threads), threaded_observer.size());
Trent Apted4d207362018-08-15 23:48:15312
313 Time start = Time::Now();
314 while (true) {
315 if ((Time::Now() - start).InMilliseconds() > kThreadRunTime)
316 break;
317
318 observer_list->Notify(FROM_HERE, &Foo::Observe, 10);
319
320 RunLoop().RunUntilIdle();
321 }
322
Sami Kyostila21f4d4c2018-11-29 11:11:36323 scoped_task_environment.RunUntilIdle();
Trent Apted4d207362018-08-15 23:48:15324}
325
Wezc1143172019-01-21 18:05:41326TEST(ObserverListThreadSafeTest, CrossThreadObserver) {
Trent Apted4d207362018-08-15 23:48:15327 // Use 7 observer threads. Notifications only come from the main thread.
328 ThreadSafeObserverHarness(7, false);
329}
330
331TEST(ObserverListThreadSafeTest, CrossThreadNotifications) {
332 // Use 3 observer threads. Notifications will fire from the main thread and
333 // all 3 observer threads.
334 ThreadSafeObserverHarness(3, true);
335}
336
Sami Kyostila3f49cb572018-11-19 13:01:09337TEST(ObserverListThreadSafeTest, OutlivesTaskEnvironment) {
338 Optional<test::ScopedTaskEnvironment> scoped_task_environment(in_place);
Trent Apted4d207362018-08-15 23:48:15339 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
340 new ObserverListThreadSafe<Foo>);
341
342 Adder a(1);
343 observer_list->AddObserver(&a);
Sami Kyostila3f49cb572018-11-19 13:01:09344 scoped_task_environment.reset();
Trent Apted4d207362018-08-15 23:48:15345 // Test passes if we don't crash here.
346 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
347}
348
349namespace {
350
351class SequenceVerificationObserver : public Foo {
352 public:
353 explicit SequenceVerificationObserver(
354 scoped_refptr<SequencedTaskRunner> task_runner)
355 : task_runner_(std::move(task_runner)) {}
356 ~SequenceVerificationObserver() override = default;
357
358 void Observe(int x) override {
359 called_on_valid_sequence_ = task_runner_->RunsTasksInCurrentSequence();
360 }
361
362 bool called_on_valid_sequence() const { return called_on_valid_sequence_; }
363
364 private:
365 const scoped_refptr<SequencedTaskRunner> task_runner_;
366 bool called_on_valid_sequence_ = false;
367
368 DISALLOW_COPY_AND_ASSIGN(SequenceVerificationObserver);
369};
370
371} // namespace
372
373// Verify that observers are notified on the correct sequence.
374TEST(ObserverListThreadSafeTest, NotificationOnValidSequence) {
375 test::ScopedTaskEnvironment scoped_task_environment;
376
377 auto task_runner_1 = CreateSequencedTaskRunnerWithTraits(TaskTraits());
378 auto task_runner_2 = CreateSequencedTaskRunnerWithTraits(TaskTraits());
379
380 auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>();
381
382 SequenceVerificationObserver observer_1(task_runner_1);
383 SequenceVerificationObserver observer_2(task_runner_2);
384
385 task_runner_1->PostTask(FROM_HERE,
386 BindOnce(&ObserverListThreadSafe<Foo>::AddObserver,
387 observer_list, Unretained(&observer_1)));
388 task_runner_2->PostTask(FROM_HERE,
389 BindOnce(&ObserverListThreadSafe<Foo>::AddObserver,
390 observer_list, Unretained(&observer_2)));
391
392 TaskScheduler::GetInstance()->FlushForTesting();
393
394 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
395
396 TaskScheduler::GetInstance()->FlushForTesting();
397
398 EXPECT_TRUE(observer_1.called_on_valid_sequence());
399 EXPECT_TRUE(observer_2.called_on_valid_sequence());
400}
401
402// Verify that when an observer is added to a NOTIFY_ALL ObserverListThreadSafe
403// from a notification, it is itself notified.
404TEST(ObserverListThreadSafeTest, AddObserverFromNotificationNotifyAll) {
405 test::ScopedTaskEnvironment scoped_task_environment;
406 auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>();
407
408 Adder observer_added_from_notification(1);
409
410 AddInObserve initial_observer(observer_list.get());
411 initial_observer.SetToAdd(&observer_added_from_notification);
412 observer_list->AddObserver(&initial_observer);
413
414 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
415
416 base::RunLoop().RunUntilIdle();
417
418 EXPECT_EQ(1, observer_added_from_notification.GetValue());
419}
420
421namespace {
422
423class RemoveWhileNotificationIsRunningObserver : public Foo {
424 public:
425 RemoveWhileNotificationIsRunningObserver()
426 : notification_running_(WaitableEvent::ResetPolicy::AUTOMATIC,
427 WaitableEvent::InitialState::NOT_SIGNALED),
428 barrier_(WaitableEvent::ResetPolicy::AUTOMATIC,
429 WaitableEvent::InitialState::NOT_SIGNALED) {}
430 ~RemoveWhileNotificationIsRunningObserver() override = default;
431
432 void Observe(int x) override {
433 notification_running_.Signal();
434 ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives;
435 barrier_.Wait();
436 }
437
438 void WaitForNotificationRunning() { notification_running_.Wait(); }
439 void Unblock() { barrier_.Signal(); }
440
441 private:
442 WaitableEvent notification_running_;
443 WaitableEvent barrier_;
444
445 DISALLOW_COPY_AND_ASSIGN(RemoveWhileNotificationIsRunningObserver);
446};
447
448} // namespace
449
450// Verify that there is no crash when an observer is removed while it is being
451// notified.
452TEST(ObserverListThreadSafeTest, RemoveWhileNotificationIsRunning) {
453 auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>();
454 RemoveWhileNotificationIsRunningObserver observer;
455
456 WaitableEvent task_running(WaitableEvent::ResetPolicy::AUTOMATIC,
457 WaitableEvent::InitialState::NOT_SIGNALED);
458 WaitableEvent barrier(WaitableEvent::ResetPolicy::AUTOMATIC,
459 WaitableEvent::InitialState::NOT_SIGNALED);
460
461 // This must be after the declaration of |barrier| so that tasks posted to
462 // TaskScheduler can safely use |barrier|.
463 test::ScopedTaskEnvironment scoped_task_environment;
464
Etienne Pierre-Doray3879b052018-09-17 14:17:22465 CreateSequencedTaskRunnerWithTraits({MayBlock()})
466 ->PostTask(FROM_HERE,
467 base::BindOnce(&ObserverListThreadSafe<Foo>::AddObserver,
Trent Apted4d207362018-08-15 23:48:15468 observer_list, Unretained(&observer)));
469 TaskScheduler::GetInstance()->FlushForTesting();
470
471 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
472 observer.WaitForNotificationRunning();
473 observer_list->RemoveObserver(&observer);
474
475 observer.Unblock();
476}
477
478// Same as ObserverListTest.Existing, but for ObserverListThreadSafe
479TEST(ObserverListThreadSafeTest, Existing) {
Sami Kyostila3f49cb572018-11-19 13:01:09480 test::ScopedTaskEnvironment scoped_task_environment;
Trent Apted4d207362018-08-15 23:48:15481 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
482 new ObserverListThreadSafe<Foo>(ObserverListPolicy::EXISTING_ONLY));
483 Adder a(1);
484 AddInObserve b(observer_list.get());
485 Adder c(1);
486 b.SetToAdd(&c);
487
488 observer_list->AddObserver(&a);
489 observer_list->AddObserver(&b);
490
491 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
492 RunLoop().RunUntilIdle();
493
494 EXPECT_FALSE(b.to_add_);
495 // B's adder should not have been notified because it was added during
496 // notification.
497 EXPECT_EQ(0, c.total);
498
499 // Notify again to make sure b's adder is notified.
500 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
501 RunLoop().RunUntilIdle();
502 EXPECT_EQ(1, c.total);
503}
504
505} // namespace base