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 #include "content/common/one_writer_seqlock.h"
9 #include "base/atomic_ref_count.h"
10 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
11 #include "base/threading/platform_thread.h"
12 #include "testing/gtest/include/gtest/gtest.h"
16 // Basic test to make sure that basic operation works correctly.
22 class BasicSeqLockTestThread
: public PlatformThread::Delegate
{
24 BasicSeqLockTestThread() {}
27 content::OneWriterSeqLock
* seqlock
,
29 base::subtle::Atomic32
* ready
) {
34 void ThreadMain() override
{
35 while (AtomicRefCountIsZero(ready_
)) {
36 PlatformThread::YieldCurrentThread();
39 for (unsigned i
= 0; i
< 1000; ++i
) {
41 base::subtle::Atomic32 version
;
43 version
= seqlock_
->ReadBegin();
45 } while (seqlock_
->ReadRetry(version
));
47 EXPECT_EQ(copy
.a
+ 100, copy
.b
);
48 EXPECT_EQ(copy
.c
, copy
.b
+ copy
.a
);
51 AtomicRefCountDec(ready_
);
55 content::OneWriterSeqLock
* seqlock_
;
57 base::AtomicRefCount
* ready_
;
59 DISALLOW_COPY_AND_ASSIGN(BasicSeqLockTestThread
);
62 TEST(OneWriterSeqLockTest
, ManyThreads
) {
63 content::OneWriterSeqLock seqlock
;
64 TestData data
= { 0, 0, 0 };
65 base::AtomicRefCount ready
= 0;
67 ANNOTATE_BENIGN_RACE_SIZED(&data
, sizeof(data
), "Racey reads are discarded");
69 static const unsigned kNumReaderThreads
= 10;
70 BasicSeqLockTestThread threads
[kNumReaderThreads
];
71 PlatformThreadHandle handles
[kNumReaderThreads
];
73 for (unsigned i
= 0; i
< kNumReaderThreads
; ++i
)
74 threads
[i
].Init(&seqlock
, &data
, &ready
);
75 for (unsigned i
= 0; i
< kNumReaderThreads
; ++i
)
76 ASSERT_TRUE(PlatformThread::Create(0, &threads
[i
], &handles
[i
]));
78 // The main thread is the writer, and the spawned are readers.
83 data
.b
= data
.a
+ 100;
84 data
.c
= data
.b
+ data
.a
;
88 base::AtomicRefCountIncN(&ready
, kNumReaderThreads
);
90 if (AtomicRefCountIsZero(&ready
))
94 for (unsigned i
= 0; i
< kNumReaderThreads
; ++i
)
95 PlatformThread::Join(handles
[i
]);