blob: f29ce308cddb2528cacf812a89ea625ebd67c1cb [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
326#if defined(OS_FUCHSIA)
327// TODO(crbug.com/738275): This is flaky on Fuchsia.
328#define MAYBE_CrossThreadObserver DISABLED_CrossThreadObserver
329#else
330#define MAYBE_CrossThreadObserver CrossThreadObserver
331#endif
332TEST(ObserverListThreadSafeTest, MAYBE_CrossThreadObserver) {
333 // Use 7 observer threads. Notifications only come from the main thread.
334 ThreadSafeObserverHarness(7, false);
335}
336
337TEST(ObserverListThreadSafeTest, CrossThreadNotifications) {
338 // Use 3 observer threads. Notifications will fire from the main thread and
339 // all 3 observer threads.
340 ThreadSafeObserverHarness(3, true);
341}
342
Sami Kyostila3f49cb572018-11-19 13:01:09343TEST(ObserverListThreadSafeTest, OutlivesTaskEnvironment) {
344 Optional<test::ScopedTaskEnvironment> scoped_task_environment(in_place);
Trent Apted4d207362018-08-15 23:48:15345 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
346 new ObserverListThreadSafe<Foo>);
347
348 Adder a(1);
349 observer_list->AddObserver(&a);
Sami Kyostila3f49cb572018-11-19 13:01:09350 scoped_task_environment.reset();
Trent Apted4d207362018-08-15 23:48:15351 // Test passes if we don't crash here.
352 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
353}
354
355namespace {
356
357class SequenceVerificationObserver : public Foo {
358 public:
359 explicit SequenceVerificationObserver(
360 scoped_refptr<SequencedTaskRunner> task_runner)
361 : task_runner_(std::move(task_runner)) {}
362 ~SequenceVerificationObserver() override = default;
363
364 void Observe(int x) override {
365 called_on_valid_sequence_ = task_runner_->RunsTasksInCurrentSequence();
366 }
367
368 bool called_on_valid_sequence() const { return called_on_valid_sequence_; }
369
370 private:
371 const scoped_refptr<SequencedTaskRunner> task_runner_;
372 bool called_on_valid_sequence_ = false;
373
374 DISALLOW_COPY_AND_ASSIGN(SequenceVerificationObserver);
375};
376
377} // namespace
378
379// Verify that observers are notified on the correct sequence.
380TEST(ObserverListThreadSafeTest, NotificationOnValidSequence) {
381 test::ScopedTaskEnvironment scoped_task_environment;
382
383 auto task_runner_1 = CreateSequencedTaskRunnerWithTraits(TaskTraits());
384 auto task_runner_2 = CreateSequencedTaskRunnerWithTraits(TaskTraits());
385
386 auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>();
387
388 SequenceVerificationObserver observer_1(task_runner_1);
389 SequenceVerificationObserver observer_2(task_runner_2);
390
391 task_runner_1->PostTask(FROM_HERE,
392 BindOnce(&ObserverListThreadSafe<Foo>::AddObserver,
393 observer_list, Unretained(&observer_1)));
394 task_runner_2->PostTask(FROM_HERE,
395 BindOnce(&ObserverListThreadSafe<Foo>::AddObserver,
396 observer_list, Unretained(&observer_2)));
397
398 TaskScheduler::GetInstance()->FlushForTesting();
399
400 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
401
402 TaskScheduler::GetInstance()->FlushForTesting();
403
404 EXPECT_TRUE(observer_1.called_on_valid_sequence());
405 EXPECT_TRUE(observer_2.called_on_valid_sequence());
406}
407
408// Verify that when an observer is added to a NOTIFY_ALL ObserverListThreadSafe
409// from a notification, it is itself notified.
410TEST(ObserverListThreadSafeTest, AddObserverFromNotificationNotifyAll) {
411 test::ScopedTaskEnvironment scoped_task_environment;
412 auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>();
413
414 Adder observer_added_from_notification(1);
415
416 AddInObserve initial_observer(observer_list.get());
417 initial_observer.SetToAdd(&observer_added_from_notification);
418 observer_list->AddObserver(&initial_observer);
419
420 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
421
422 base::RunLoop().RunUntilIdle();
423
424 EXPECT_EQ(1, observer_added_from_notification.GetValue());
425}
426
427namespace {
428
429class RemoveWhileNotificationIsRunningObserver : public Foo {
430 public:
431 RemoveWhileNotificationIsRunningObserver()
432 : notification_running_(WaitableEvent::ResetPolicy::AUTOMATIC,
433 WaitableEvent::InitialState::NOT_SIGNALED),
434 barrier_(WaitableEvent::ResetPolicy::AUTOMATIC,
435 WaitableEvent::InitialState::NOT_SIGNALED) {}
436 ~RemoveWhileNotificationIsRunningObserver() override = default;
437
438 void Observe(int x) override {
439 notification_running_.Signal();
440 ScopedAllowBaseSyncPrimitivesForTesting allow_base_sync_primitives;
441 barrier_.Wait();
442 }
443
444 void WaitForNotificationRunning() { notification_running_.Wait(); }
445 void Unblock() { barrier_.Signal(); }
446
447 private:
448 WaitableEvent notification_running_;
449 WaitableEvent barrier_;
450
451 DISALLOW_COPY_AND_ASSIGN(RemoveWhileNotificationIsRunningObserver);
452};
453
454} // namespace
455
456// Verify that there is no crash when an observer is removed while it is being
457// notified.
458TEST(ObserverListThreadSafeTest, RemoveWhileNotificationIsRunning) {
459 auto observer_list = MakeRefCounted<ObserverListThreadSafe<Foo>>();
460 RemoveWhileNotificationIsRunningObserver observer;
461
462 WaitableEvent task_running(WaitableEvent::ResetPolicy::AUTOMATIC,
463 WaitableEvent::InitialState::NOT_SIGNALED);
464 WaitableEvent barrier(WaitableEvent::ResetPolicy::AUTOMATIC,
465 WaitableEvent::InitialState::NOT_SIGNALED);
466
467 // This must be after the declaration of |barrier| so that tasks posted to
468 // TaskScheduler can safely use |barrier|.
469 test::ScopedTaskEnvironment scoped_task_environment;
470
Etienne Pierre-Doray3879b052018-09-17 14:17:22471 CreateSequencedTaskRunnerWithTraits({MayBlock()})
472 ->PostTask(FROM_HERE,
473 base::BindOnce(&ObserverListThreadSafe<Foo>::AddObserver,
Trent Apted4d207362018-08-15 23:48:15474 observer_list, Unretained(&observer)));
475 TaskScheduler::GetInstance()->FlushForTesting();
476
477 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
478 observer.WaitForNotificationRunning();
479 observer_list->RemoveObserver(&observer);
480
481 observer.Unblock();
482}
483
484// Same as ObserverListTest.Existing, but for ObserverListThreadSafe
485TEST(ObserverListThreadSafeTest, Existing) {
Sami Kyostila3f49cb572018-11-19 13:01:09486 test::ScopedTaskEnvironment scoped_task_environment;
Trent Apted4d207362018-08-15 23:48:15487 scoped_refptr<ObserverListThreadSafe<Foo>> observer_list(
488 new ObserverListThreadSafe<Foo>(ObserverListPolicy::EXISTING_ONLY));
489 Adder a(1);
490 AddInObserve b(observer_list.get());
491 Adder c(1);
492 b.SetToAdd(&c);
493
494 observer_list->AddObserver(&a);
495 observer_list->AddObserver(&b);
496
497 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
498 RunLoop().RunUntilIdle();
499
500 EXPECT_FALSE(b.to_add_);
501 // B's adder should not have been notified because it was added during
502 // notification.
503 EXPECT_EQ(0, c.total);
504
505 // Notify again to make sure b's adder is notified.
506 observer_list->Notify(FROM_HERE, &Foo::Observe, 1);
507 RunLoop().RunUntilIdle();
508 EXPECT_EQ(1, c.total);
509}
510
511} // namespace base