blob: db4f9e7452f57c660c7d953241b38c9d20f09804 [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
Yves Gerey665174f2018-06-19 15:03:05 +020066 void Finalize() { EXPECT_EQ(1, zero_count_); }
67
Jiayang Liubef8d2d2015-03-26 14:38:46 -070068 private:
69 int zero_count_;
70};
71
72class RunnerBase : public MessageHandler {
73 public:
74 explicit RunnerBase(int value)
75 : threads_active_(0),
76 start_event_(true, false),
77 done_event_(true, false),
78 shared_value_(value) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079
80 bool Run() {
81 // Signal all threads to start.
82 start_event_.Set();
83
84 // Wait for all threads to finish.
85 return done_event_.Wait(kLongTime);
86 }
87
Yves Gerey665174f2018-06-19 15:03:05 +020088 void SetExpectedThreadCount(int count) { threads_active_ = count; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000089
Jiayang Liubef8d2d2015-03-26 14:38:46 -070090 int shared_value() const { return shared_value_; }
91
92 protected:
93 // Derived classes must override OnMessage, and call BeforeStart and AfterEnd
94 // at the beginning and the end of OnMessage respectively.
Yves Gerey665174f2018-06-19 15:03:05 +020095 void BeforeStart() { ASSERT_TRUE(start_event_.Wait(kLongTime)); }
Jiayang Liubef8d2d2015-03-26 14:38:46 -070096
97 // Returns true if all threads have finished.
98 bool AfterEnd() {
99 if (AtomicOps::Decrement(&threads_active_) == 0) {
100 done_event_.Set();
101 return true;
102 }
103 return false;
104 }
105
106 int threads_active_;
107 Event start_event_;
108 Event done_event_;
109 int shared_value_;
110};
111
danilchap3c6abd22017-09-06 05:46:29 -0700112class RTC_LOCKABLE CriticalSectionLock {
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700113 public:
danilchap3c6abd22017-09-06 05:46:29 -0700114 void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { cs_.Enter(); }
115 void Unlock() RTC_UNLOCK_FUNCTION() { cs_.Leave(); }
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700116
117 private:
118 CriticalSection cs_;
119};
120
121template <class Lock>
122class LockRunner : public RunnerBase {
123 public:
124 LockRunner() : RunnerBase(0) {}
125
126 void OnMessage(Message* msg) override {
127 BeforeStart();
128
129 lock_.Lock();
130
131 EXPECT_EQ(0, shared_value_);
132 int old = shared_value_;
133
134 // Use a loop to increase the chance of race.
135 for (int i = 0; i < kOperationsToRun; ++i) {
136 ++shared_value_;
137 }
138 EXPECT_EQ(old + kOperationsToRun, shared_value_);
139 shared_value_ = 0;
140
141 lock_.Unlock();
142
143 AfterEnd();
144 }
145
146 private:
147 Lock lock_;
148};
149
150template <class Op, class Verifier>
151class AtomicOpRunner : public RunnerBase {
152 public:
153 explicit AtomicOpRunner(int initial_value) : RunnerBase(initial_value) {}
154
155 void OnMessage(Message* msg) override {
156 BeforeStart();
157
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000158 std::vector<int> values;
159 values.reserve(kOperationsToRun);
160
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700161 // Generate a bunch of values by updating shared_value_ atomically.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000162 for (int i = 0; i < kOperationsToRun; ++i) {
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700163 values.push_back(Op::AtomicOp(&shared_value_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164 }
165
Yves Gerey665174f2018-06-19 15:03:05 +0200166 { // Add them all to the set.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 CritScope cs(&all_values_crit_);
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700168 verifier_.Verify(values);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169 }
170
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700171 if (AfterEnd()) {
172 verifier_.Finalize();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173 }
174 }
175
176 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177 CriticalSection all_values_crit_;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700178 Verifier verifier_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179};
180
181struct IncrementOp {
182 static int AtomicOp(int* i) { return AtomicOps::Increment(i); }
183};
184
185struct DecrementOp {
186 static int AtomicOp(int* i) { return AtomicOps::Decrement(i); }
187};
188
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700189struct CompareAndSwapOp {
190 static int AtomicOp(int* i) { return AtomicOps::CompareAndSwap(i, 0, 1); }
191};
192
nisseb9c2f7c2017-04-20 02:23:08 -0700193void StartThreads(std::vector<std::unique_ptr<Thread>>* threads,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000194 MessageHandler* handler) {
195 for (int i = 0; i < kNumThreads; ++i) {
tommie7251592017-07-14 14:44:46 -0700196 std::unique_ptr<Thread> thread(Thread::Create());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197 thread->Start();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700198 thread->Post(RTC_FROM_HERE, handler);
nisseb9c2f7c2017-04-20 02:23:08 -0700199 threads->push_back(std::move(thread));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200 }
201}
202
203} // namespace
204
205TEST(AtomicOpsTest, Simple) {
206 int value = 0;
207 EXPECT_EQ(1, AtomicOps::Increment(&value));
208 EXPECT_EQ(1, value);
209 EXPECT_EQ(2, AtomicOps::Increment(&value));
210 EXPECT_EQ(2, value);
211 EXPECT_EQ(1, AtomicOps::Decrement(&value));
212 EXPECT_EQ(1, value);
213 EXPECT_EQ(0, AtomicOps::Decrement(&value));
214 EXPECT_EQ(0, value);
215}
216
Peter Boström455a2522015-12-18 17:00:25 +0100217TEST(AtomicOpsTest, SimplePtr) {
218 class Foo {};
219 Foo* volatile foo = nullptr;
jbauch555604a2016-04-26 03:13:22 -0700220 std::unique_ptr<Foo> a(new Foo());
221 std::unique_ptr<Foo> b(new Foo());
Peter Boström455a2522015-12-18 17:00:25 +0100222 // Reading the initial value should work as expected.
223 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == nullptr);
224 // Setting using compare and swap should work.
225 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
226 &foo, static_cast<Foo*>(nullptr), a.get()) == nullptr);
227 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
228 // Setting another value but with the wrong previous pointer should fail
229 // (remain a).
230 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
231 &foo, static_cast<Foo*>(nullptr), b.get()) == a.get());
232 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
233 // Replacing a with b should work.
234 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(&foo, a.get(), b.get()) ==
235 a.get());
236 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == b.get());
237}
238
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000239TEST(AtomicOpsTest, Increment) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000240 // Create and start lots of threads.
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700241 AtomicOpRunner<IncrementOp, UniqueValueVerifier> runner(0);
nisseb9c2f7c2017-04-20 02:23:08 -0700242 std::vector<std::unique_ptr<Thread>> threads;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000243 StartThreads(&threads, &runner);
244 runner.SetExpectedThreadCount(kNumThreads);
245
246 // Release the hounds!
247 EXPECT_TRUE(runner.Run());
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700248 EXPECT_EQ(kOperationsToRun * kNumThreads, runner.shared_value());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249}
250
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000251TEST(AtomicOpsTest, Decrement) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252 // Create and start lots of threads.
Yves Gerey665174f2018-06-19 15:03:05 +0200253 AtomicOpRunner<DecrementOp, UniqueValueVerifier> runner(kOperationsToRun *
254 kNumThreads);
nisseb9c2f7c2017-04-20 02:23:08 -0700255 std::vector<std::unique_ptr<Thread>> threads;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256 StartThreads(&threads, &runner);
257 runner.SetExpectedThreadCount(kNumThreads);
258
259 // Release the hounds!
260 EXPECT_TRUE(runner.Run());
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700261 EXPECT_EQ(0, runner.shared_value());
262}
263
264TEST(AtomicOpsTest, CompareAndSwap) {
265 // Create and start lots of threads.
266 AtomicOpRunner<CompareAndSwapOp, CompareAndSwapVerifier> runner(0);
nisseb9c2f7c2017-04-20 02:23:08 -0700267 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700268 StartThreads(&threads, &runner);
269 runner.SetExpectedThreadCount(kNumThreads);
270
271 // Release the hounds!
272 EXPECT_TRUE(runner.Run());
273 EXPECT_EQ(1, runner.shared_value());
274}
275
276TEST(GlobalLockTest, Basic) {
277 // Create and start lots of threads.
278 LockRunner<GlobalLock> runner;
nisseb9c2f7c2017-04-20 02:23:08 -0700279 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700280 StartThreads(&threads, &runner);
281 runner.SetExpectedThreadCount(kNumThreads);
282
283 // Release the hounds!
284 EXPECT_TRUE(runner.Run());
285 EXPECT_EQ(0, runner.shared_value());
286}
287
288TEST(CriticalSectionTest, Basic) {
289 // Create and start lots of threads.
290 LockRunner<CriticalSectionLock> runner;
nisseb9c2f7c2017-04-20 02:23:08 -0700291 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700292 StartThreads(&threads, &runner);
293 runner.SetExpectedThreadCount(kNumThreads);
294
295 // Release the hounds!
296 EXPECT_TRUE(runner.Run());
297 EXPECT_EQ(0, runner.shared_value());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298}
299
tommied281e92016-01-21 23:47:25 -0800300class PerfTestData {
301 public:
302 PerfTestData(int expected_count, Event* event)
Yves Gerey665174f2018-06-19 15:03:05 +0200303 : cache_line_barrier_1_(),
304 cache_line_barrier_2_(),
305 expected_count_(expected_count),
306 event_(event) {
tommied281e92016-01-21 23:47:25 -0800307 cache_line_barrier_1_[0]++; // Avoid 'is not used'.
308 cache_line_barrier_2_[0]++; // Avoid 'is not used'.
309 }
310 ~PerfTestData() {}
311
312 void AddToCounter(int add) {
313 rtc::CritScope cs(&lock_);
314 my_counter_ += add;
315 if (my_counter_ == expected_count_)
316 event_->Set();
317 }
318
319 int64_t total() const {
320 // Assume that only one thread is running now.
321 return my_counter_;
322 }
323
324 private:
325 uint8_t cache_line_barrier_1_[64];
326 CriticalSection lock_;
327 uint8_t cache_line_barrier_2_[64];
328 int64_t my_counter_ = 0;
329 const int expected_count_;
330 Event* const event_;
331};
332
333class PerfTestThread {
334 public:
335 PerfTestThread() : thread_(&ThreadFunc, this, "CsPerf") {}
336
337 void Start(PerfTestData* data, int repeats, int id) {
338 RTC_DCHECK(!thread_.IsRunning());
339 RTC_DCHECK(!data_);
340 data_ = data;
341 repeats_ = repeats;
342 my_id_ = id;
343 thread_.Start();
344 }
345
346 void Stop() {
347 RTC_DCHECK(thread_.IsRunning());
348 RTC_DCHECK(data_);
349 thread_.Stop();
350 repeats_ = 0;
351 data_ = nullptr;
352 my_id_ = 0;
353 }
354
355 private:
356 static bool ThreadFunc(void* param) {
357 PerfTestThread* me = static_cast<PerfTestThread*>(param);
358 for (int i = 0; i < me->repeats_; ++i)
359 me->data_->AddToCounter(me->my_id_);
360 return false;
361 }
362
363 PlatformThread thread_;
364 PerfTestData* data_ = nullptr;
365 int repeats_ = 0;
366 int my_id_ = 0;
367};
368
369// Comparison of output of this test as tested on a MacBook Pro Retina, 15-inch,
370// Mid 2014, 2,8 GHz Intel Core i7, 16 GB 1600 MHz DDR3,
371// running OS X El Capitan, 10.11.2.
372//
373// Native mutex implementation:
374// Approximate CPU usage:
375// System: ~16%
376// User mode: ~1.3%
377// Idle: ~82%
378// Unit test output:
379// [ OK ] CriticalSectionTest.Performance (234545 ms)
380//
381// Special partially spin lock based implementation:
382// Approximate CPU usage:
383// System: ~75%
384// User mode: ~16%
385// Idle: ~8%
386// Unit test output:
387// [ OK ] CriticalSectionTest.Performance (2107 ms)
388//
389// The test is disabled by default to avoid unecessarily loading the bots.
390TEST(CriticalSectionTest, DISABLED_Performance) {
391 PerfTestThread threads[8];
392 Event event(false, false);
393
394 static const int kThreadRepeats = 10000000;
395 static const int kExpectedCount = kThreadRepeats * arraysize(threads);
396 PerfTestData test_data(kExpectedCount, &event);
397
398 for (auto& t : threads)
399 t.Start(&test_data, kThreadRepeats, 1);
400
401 event.Wait(Event::kForever);
402
403 for (auto& t : threads)
404 t.Stop();
405}
406
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000407} // namespace rtc