blob: 679250435314fdb174b57721804124a71ee87e08 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2014 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
jbauch555604a2016-04-26 03:13:22 -070011#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012#include <set>
13#include <vector>
14
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020015#include "rtc_base/arraysize.h"
Tommi8d2c5a82018-03-19 11:12:48 +010016#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "rtc_base/checks.h"
18#include "rtc_base/criticalsection.h"
19#include "rtc_base/event.h"
20#include "rtc_base/gunit.h"
21#include "rtc_base/platform_thread.h"
22#include "rtc_base/thread.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023
24namespace rtc {
25
26namespace {
27
28const int kLongTime = 10000; // 10 seconds
29const int kNumThreads = 16;
30const int kOperationsToRun = 1000;
31
Jiayang Liubef8d2d2015-03-26 14:38:46 -070032class UniqueValueVerifier {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000033 public:
Jiayang Liubef8d2d2015-03-26 14:38:46 -070034 void Verify(const std::vector<int>& values) {
35 for (size_t i = 0; i < values.size(); ++i) {
36 std::pair<std::set<int>::iterator, bool> result =
37 all_values_.insert(values[i]);
38 // Each value should only be taken by one thread, so if this value
39 // has already been added, something went wrong.
40 EXPECT_TRUE(result.second)
41 << " Thread=" << Thread::Current() << " value=" << values[i];
42 }
43 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044
Jiayang Liubef8d2d2015-03-26 14:38:46 -070045 void Finalize() {}
46
47 private:
48 std::set<int> all_values_;
49};
50
51class CompareAndSwapVerifier {
52 public:
53 CompareAndSwapVerifier() : zero_count_(0) {}
54
55 void Verify(const std::vector<int>& values) {
56 for (auto v : values) {
57 if (v == 0) {
58 EXPECT_EQ(0, zero_count_) << "Thread=" << Thread::Current();
59 ++zero_count_;
60 } else {
61 EXPECT_EQ(1, v) << " Thread=" << Thread::Current();
62 }
63 }
64 }
65
66 void Finalize() {
67 EXPECT_EQ(1, zero_count_);
68 }
69 private:
70 int zero_count_;
71};
72
73class RunnerBase : public MessageHandler {
74 public:
75 explicit RunnerBase(int value)
76 : threads_active_(0),
77 start_event_(true, false),
78 done_event_(true, false),
79 shared_value_(value) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080
81 bool Run() {
82 // Signal all threads to start.
83 start_event_.Set();
84
85 // Wait for all threads to finish.
86 return done_event_.Wait(kLongTime);
87 }
88
89 void SetExpectedThreadCount(int count) {
90 threads_active_ = count;
91 }
92
Jiayang Liubef8d2d2015-03-26 14:38:46 -070093 int shared_value() const { return shared_value_; }
94
95 protected:
96 // Derived classes must override OnMessage, and call BeforeStart and AfterEnd
97 // at the beginning and the end of OnMessage respectively.
98 void BeforeStart() {
99 ASSERT_TRUE(start_event_.Wait(kLongTime));
100 }
101
102 // Returns true if all threads have finished.
103 bool AfterEnd() {
104 if (AtomicOps::Decrement(&threads_active_) == 0) {
105 done_event_.Set();
106 return true;
107 }
108 return false;
109 }
110
111 int threads_active_;
112 Event start_event_;
113 Event done_event_;
114 int shared_value_;
115};
116
danilchap3c6abd22017-09-06 05:46:29 -0700117class RTC_LOCKABLE CriticalSectionLock {
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700118 public:
danilchap3c6abd22017-09-06 05:46:29 -0700119 void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { cs_.Enter(); }
120 void Unlock() RTC_UNLOCK_FUNCTION() { cs_.Leave(); }
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700121
122 private:
123 CriticalSection cs_;
124};
125
126template <class Lock>
127class LockRunner : public RunnerBase {
128 public:
129 LockRunner() : RunnerBase(0) {}
130
131 void OnMessage(Message* msg) override {
132 BeforeStart();
133
134 lock_.Lock();
135
136 EXPECT_EQ(0, shared_value_);
137 int old = shared_value_;
138
139 // Use a loop to increase the chance of race.
140 for (int i = 0; i < kOperationsToRun; ++i) {
141 ++shared_value_;
142 }
143 EXPECT_EQ(old + kOperationsToRun, shared_value_);
144 shared_value_ = 0;
145
146 lock_.Unlock();
147
148 AfterEnd();
149 }
150
151 private:
152 Lock lock_;
153};
154
155template <class Op, class Verifier>
156class AtomicOpRunner : public RunnerBase {
157 public:
158 explicit AtomicOpRunner(int initial_value) : RunnerBase(initial_value) {}
159
160 void OnMessage(Message* msg) override {
161 BeforeStart();
162
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000163 std::vector<int> values;
164 values.reserve(kOperationsToRun);
165
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700166 // Generate a bunch of values by updating shared_value_ atomically.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 for (int i = 0; i < kOperationsToRun; ++i) {
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700168 values.push_back(Op::AtomicOp(&shared_value_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169 }
170
171 { // Add them all to the set.
172 CritScope cs(&all_values_crit_);
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700173 verifier_.Verify(values);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000174 }
175
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700176 if (AfterEnd()) {
177 verifier_.Finalize();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178 }
179 }
180
181 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182 CriticalSection all_values_crit_;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700183 Verifier verifier_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184};
185
186struct IncrementOp {
187 static int AtomicOp(int* i) { return AtomicOps::Increment(i); }
188};
189
190struct DecrementOp {
191 static int AtomicOp(int* i) { return AtomicOps::Decrement(i); }
192};
193
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700194struct CompareAndSwapOp {
195 static int AtomicOp(int* i) { return AtomicOps::CompareAndSwap(i, 0, 1); }
196};
197
nisseb9c2f7c2017-04-20 02:23:08 -0700198void StartThreads(std::vector<std::unique_ptr<Thread>>* threads,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199 MessageHandler* handler) {
200 for (int i = 0; i < kNumThreads; ++i) {
tommie7251592017-07-14 14:44:46 -0700201 std::unique_ptr<Thread> thread(Thread::Create());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000202 thread->Start();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700203 thread->Post(RTC_FROM_HERE, handler);
nisseb9c2f7c2017-04-20 02:23:08 -0700204 threads->push_back(std::move(thread));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205 }
206}
207
208} // namespace
209
210TEST(AtomicOpsTest, Simple) {
211 int value = 0;
212 EXPECT_EQ(1, AtomicOps::Increment(&value));
213 EXPECT_EQ(1, value);
214 EXPECT_EQ(2, AtomicOps::Increment(&value));
215 EXPECT_EQ(2, value);
216 EXPECT_EQ(1, AtomicOps::Decrement(&value));
217 EXPECT_EQ(1, value);
218 EXPECT_EQ(0, AtomicOps::Decrement(&value));
219 EXPECT_EQ(0, value);
220}
221
Peter Boström455a2522015-12-18 17:00:25 +0100222TEST(AtomicOpsTest, SimplePtr) {
223 class Foo {};
224 Foo* volatile foo = nullptr;
jbauch555604a2016-04-26 03:13:22 -0700225 std::unique_ptr<Foo> a(new Foo());
226 std::unique_ptr<Foo> b(new Foo());
Peter Boström455a2522015-12-18 17:00:25 +0100227 // Reading the initial value should work as expected.
228 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == nullptr);
229 // Setting using compare and swap should work.
230 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
231 &foo, static_cast<Foo*>(nullptr), a.get()) == nullptr);
232 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
233 // Setting another value but with the wrong previous pointer should fail
234 // (remain a).
235 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
236 &foo, static_cast<Foo*>(nullptr), b.get()) == a.get());
237 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
238 // Replacing a with b should work.
239 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(&foo, a.get(), b.get()) ==
240 a.get());
241 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == b.get());
242}
243
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000244TEST(AtomicOpsTest, Increment) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000245 // Create and start lots of threads.
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700246 AtomicOpRunner<IncrementOp, UniqueValueVerifier> runner(0);
nisseb9c2f7c2017-04-20 02:23:08 -0700247 std::vector<std::unique_ptr<Thread>> threads;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000248 StartThreads(&threads, &runner);
249 runner.SetExpectedThreadCount(kNumThreads);
250
251 // Release the hounds!
252 EXPECT_TRUE(runner.Run());
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700253 EXPECT_EQ(kOperationsToRun * kNumThreads, runner.shared_value());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254}
255
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000256TEST(AtomicOpsTest, Decrement) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000257 // Create and start lots of threads.
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700258 AtomicOpRunner<DecrementOp, UniqueValueVerifier> runner(
259 kOperationsToRun * kNumThreads);
nisseb9c2f7c2017-04-20 02:23:08 -0700260 std::vector<std::unique_ptr<Thread>> threads;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 StartThreads(&threads, &runner);
262 runner.SetExpectedThreadCount(kNumThreads);
263
264 // Release the hounds!
265 EXPECT_TRUE(runner.Run());
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700266 EXPECT_EQ(0, runner.shared_value());
267}
268
269TEST(AtomicOpsTest, CompareAndSwap) {
270 // Create and start lots of threads.
271 AtomicOpRunner<CompareAndSwapOp, CompareAndSwapVerifier> runner(0);
nisseb9c2f7c2017-04-20 02:23:08 -0700272 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700273 StartThreads(&threads, &runner);
274 runner.SetExpectedThreadCount(kNumThreads);
275
276 // Release the hounds!
277 EXPECT_TRUE(runner.Run());
278 EXPECT_EQ(1, runner.shared_value());
279}
280
281TEST(GlobalLockTest, Basic) {
282 // Create and start lots of threads.
283 LockRunner<GlobalLock> runner;
nisseb9c2f7c2017-04-20 02:23:08 -0700284 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700285 StartThreads(&threads, &runner);
286 runner.SetExpectedThreadCount(kNumThreads);
287
288 // Release the hounds!
289 EXPECT_TRUE(runner.Run());
290 EXPECT_EQ(0, runner.shared_value());
291}
292
293TEST(CriticalSectionTest, Basic) {
294 // Create and start lots of threads.
295 LockRunner<CriticalSectionLock> runner;
nisseb9c2f7c2017-04-20 02:23:08 -0700296 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700297 StartThreads(&threads, &runner);
298 runner.SetExpectedThreadCount(kNumThreads);
299
300 // Release the hounds!
301 EXPECT_TRUE(runner.Run());
302 EXPECT_EQ(0, runner.shared_value());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000303}
304
tommied281e92016-01-21 23:47:25 -0800305class PerfTestData {
306 public:
307 PerfTestData(int expected_count, Event* event)
308 : cache_line_barrier_1_(), cache_line_barrier_2_(),
309 expected_count_(expected_count), event_(event) {
310 cache_line_barrier_1_[0]++; // Avoid 'is not used'.
311 cache_line_barrier_2_[0]++; // Avoid 'is not used'.
312 }
313 ~PerfTestData() {}
314
315 void AddToCounter(int add) {
316 rtc::CritScope cs(&lock_);
317 my_counter_ += add;
318 if (my_counter_ == expected_count_)
319 event_->Set();
320 }
321
322 int64_t total() const {
323 // Assume that only one thread is running now.
324 return my_counter_;
325 }
326
327 private:
328 uint8_t cache_line_barrier_1_[64];
329 CriticalSection lock_;
330 uint8_t cache_line_barrier_2_[64];
331 int64_t my_counter_ = 0;
332 const int expected_count_;
333 Event* const event_;
334};
335
336class PerfTestThread {
337 public:
338 PerfTestThread() : thread_(&ThreadFunc, this, "CsPerf") {}
339
340 void Start(PerfTestData* data, int repeats, int id) {
341 RTC_DCHECK(!thread_.IsRunning());
342 RTC_DCHECK(!data_);
343 data_ = data;
344 repeats_ = repeats;
345 my_id_ = id;
346 thread_.Start();
347 }
348
349 void Stop() {
350 RTC_DCHECK(thread_.IsRunning());
351 RTC_DCHECK(data_);
352 thread_.Stop();
353 repeats_ = 0;
354 data_ = nullptr;
355 my_id_ = 0;
356 }
357
358 private:
359 static bool ThreadFunc(void* param) {
360 PerfTestThread* me = static_cast<PerfTestThread*>(param);
361 for (int i = 0; i < me->repeats_; ++i)
362 me->data_->AddToCounter(me->my_id_);
363 return false;
364 }
365
366 PlatformThread thread_;
367 PerfTestData* data_ = nullptr;
368 int repeats_ = 0;
369 int my_id_ = 0;
370};
371
372// Comparison of output of this test as tested on a MacBook Pro Retina, 15-inch,
373// Mid 2014, 2,8 GHz Intel Core i7, 16 GB 1600 MHz DDR3,
374// running OS X El Capitan, 10.11.2.
375//
376// Native mutex implementation:
377// Approximate CPU usage:
378// System: ~16%
379// User mode: ~1.3%
380// Idle: ~82%
381// Unit test output:
382// [ OK ] CriticalSectionTest.Performance (234545 ms)
383//
384// Special partially spin lock based implementation:
385// Approximate CPU usage:
386// System: ~75%
387// User mode: ~16%
388// Idle: ~8%
389// Unit test output:
390// [ OK ] CriticalSectionTest.Performance (2107 ms)
391//
392// The test is disabled by default to avoid unecessarily loading the bots.
393TEST(CriticalSectionTest, DISABLED_Performance) {
394 PerfTestThread threads[8];
395 Event event(false, false);
396
397 static const int kThreadRepeats = 10000000;
398 static const int kExpectedCount = kThreadRepeats * arraysize(threads);
399 PerfTestData test_data(kExpectedCount, &event);
400
401 for (auto& t : threads)
402 t.Start(&test_data, kThreadRepeats, 1);
403
404 event.Wait(Event::kForever);
405
406 for (auto& t : threads)
407 t.Stop();
408}
409
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000410} // namespace rtc