blob: cf17a84e67a36af789c4fe453b63c63ff3de46b1 [file] [log] [blame]
[email protected]30039e62008-09-08 14:11:131// Copyright (c) 2008 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/at_exit.h"
6#include "base/atomic_sequence_num.h"
7#include "base/lazy_instance.h"
8#include "base/simple_thread.h"
9#include "testing/gtest/include/gtest/gtest.h"
10
11namespace {
12
[email protected]30039e62008-09-08 14:11:1313base::AtomicSequenceNumber constructed_seq_(base::LINKER_INITIALIZED);
14base::AtomicSequenceNumber destructed_seq_(base::LINKER_INITIALIZED);
15
16class ConstructAndDestructLogger {
17 public:
18 ConstructAndDestructLogger() {
19 constructed_seq_.GetNext();
20 }
21 ~ConstructAndDestructLogger() {
22 destructed_seq_.GetNext();
23 }
24};
25
26class SlowConstructor {
27 public:
28 SlowConstructor() : some_int_(0) {
29 PlatformThread::Sleep(1000); // Sleep for 1 second to try to cause a race.
30 ++constructed;
31 some_int_ = 12;
32 }
33 int some_int() const { return some_int_; }
34
35 static int constructed;
36 private:
37 int some_int_;
38};
39
40int SlowConstructor::constructed = 0;
41
42class SlowDelegate : public base::DelegateSimpleThread::Delegate {
43 public:
44 SlowDelegate(base::LazyInstance<SlowConstructor>* lazy) : lazy_(lazy) { }
45 virtual void Run() {
46 EXPECT_EQ(12, lazy_->Get().some_int());
47 EXPECT_EQ(12, lazy_->Pointer()->some_int());
48 }
49
50 private:
51 base::LazyInstance<SlowConstructor>* lazy_;
52};
53
54} // namespace
55
56static base::LazyInstance<ConstructAndDestructLogger> lazy_logger(
57 base::LINKER_INITIALIZED);
58
59TEST(LazyInstanceTest, Basic) {
60 {
[email protected]4ea927b2009-11-19 09:11:3961 base::ShadowingAtExitManager shadow;
[email protected]30039e62008-09-08 14:11:1362
63 EXPECT_EQ(0, constructed_seq_.GetNext());
64 EXPECT_EQ(0, destructed_seq_.GetNext());
65
66 lazy_logger.Get();
67 EXPECT_EQ(2, constructed_seq_.GetNext());
68 EXPECT_EQ(1, destructed_seq_.GetNext());
69
70 lazy_logger.Pointer();
71 EXPECT_EQ(3, constructed_seq_.GetNext());
72 EXPECT_EQ(2, destructed_seq_.GetNext());
[email protected]52a261f2009-03-03 15:01:1273 }
[email protected]30039e62008-09-08 14:11:1374 EXPECT_EQ(4, constructed_seq_.GetNext());
75 EXPECT_EQ(4, destructed_seq_.GetNext());
76}
77
78static base::LazyInstance<SlowConstructor> lazy_slow(base::LINKER_INITIALIZED);
79
80TEST(LazyInstanceTest, ConstructorThreadSafety) {
81 {
[email protected]4ea927b2009-11-19 09:11:3982 base::ShadowingAtExitManager shadow;
[email protected]30039e62008-09-08 14:11:1383
84 SlowDelegate delegate(&lazy_slow);
85 EXPECT_EQ(0, SlowConstructor::constructed);
86
87 base::DelegateSimpleThreadPool pool("lazy_instance_cons", 5);
88 pool.AddWork(&delegate, 20);
89 EXPECT_EQ(0, SlowConstructor::constructed);
90
91 pool.Start();
92 pool.JoinAll();
93 EXPECT_EQ(1, SlowConstructor::constructed);
94 }
95}