blob: e988046c266eb4f7ea4c91dbaf50a25d87a94b6d [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
Yves Gerey3e707812018-11-28 16:47:49 +010011#include <stddef.h>
12#include <stdint.h>
jbauch555604a2016-04-26 03:13:22 -070013#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000014#include <set>
Yves Gerey3e707812018-11-28 16:47:49 +010015#include <utility>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000016#include <vector>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/arraysize.h"
Steve Anton10542f22019-01-11 09:11:00 -080019#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010023#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/message_handler.h"
25#include "rtc_base/message_queue.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/platform_thread.h"
27#include "rtc_base/thread.h"
Yves Gerey3e707812018-11-28 16:47:49 +010028#include "test/gtest.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029
30namespace rtc {
31
32namespace {
33
34const int kLongTime = 10000; // 10 seconds
35const int kNumThreads = 16;
36const int kOperationsToRun = 1000;
37
Jiayang Liubef8d2d2015-03-26 14:38:46 -070038class UniqueValueVerifier {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039 public:
Jiayang Liubef8d2d2015-03-26 14:38:46 -070040 void Verify(const std::vector<int>& values) {
41 for (size_t i = 0; i < values.size(); ++i) {
42 std::pair<std::set<int>::iterator, bool> result =
43 all_values_.insert(values[i]);
44 // Each value should only be taken by one thread, so if this value
45 // has already been added, something went wrong.
46 EXPECT_TRUE(result.second)
47 << " Thread=" << Thread::Current() << " value=" << values[i];
48 }
49 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050
Jiayang Liubef8d2d2015-03-26 14:38:46 -070051 void Finalize() {}
52
53 private:
54 std::set<int> all_values_;
55};
56
57class CompareAndSwapVerifier {
58 public:
59 CompareAndSwapVerifier() : zero_count_(0) {}
60
61 void Verify(const std::vector<int>& values) {
62 for (auto v : values) {
63 if (v == 0) {
64 EXPECT_EQ(0, zero_count_) << "Thread=" << Thread::Current();
65 ++zero_count_;
66 } else {
67 EXPECT_EQ(1, v) << " Thread=" << Thread::Current();
68 }
69 }
70 }
71
Yves Gerey665174f2018-06-19 15:03:05 +020072 void Finalize() { EXPECT_EQ(1, zero_count_); }
73
Jiayang Liubef8d2d2015-03-26 14:38:46 -070074 private:
75 int zero_count_;
76};
77
78class RunnerBase : public MessageHandler {
79 public:
80 explicit RunnerBase(int value)
81 : threads_active_(0),
82 start_event_(true, false),
83 done_event_(true, false),
84 shared_value_(value) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085
86 bool Run() {
87 // Signal all threads to start.
88 start_event_.Set();
89
90 // Wait for all threads to finish.
91 return done_event_.Wait(kLongTime);
92 }
93
Yves Gerey665174f2018-06-19 15:03:05 +020094 void SetExpectedThreadCount(int count) { threads_active_ = count; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000095
Jiayang Liubef8d2d2015-03-26 14:38:46 -070096 int shared_value() const { return shared_value_; }
97
98 protected:
99 // Derived classes must override OnMessage, and call BeforeStart and AfterEnd
100 // at the beginning and the end of OnMessage respectively.
Yves Gerey665174f2018-06-19 15:03:05 +0200101 void BeforeStart() { ASSERT_TRUE(start_event_.Wait(kLongTime)); }
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700102
103 // Returns true if all threads have finished.
104 bool AfterEnd() {
105 if (AtomicOps::Decrement(&threads_active_) == 0) {
106 done_event_.Set();
107 return true;
108 }
109 return false;
110 }
111
112 int threads_active_;
113 Event start_event_;
114 Event done_event_;
115 int shared_value_;
116};
117
danilchap3c6abd22017-09-06 05:46:29 -0700118class RTC_LOCKABLE CriticalSectionLock {
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700119 public:
danilchap3c6abd22017-09-06 05:46:29 -0700120 void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { cs_.Enter(); }
121 void Unlock() RTC_UNLOCK_FUNCTION() { cs_.Leave(); }
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700122
123 private:
124 CriticalSection cs_;
125};
126
127template <class Lock>
128class LockRunner : public RunnerBase {
129 public:
130 LockRunner() : RunnerBase(0) {}
131
132 void OnMessage(Message* msg) override {
133 BeforeStart();
134
135 lock_.Lock();
136
137 EXPECT_EQ(0, shared_value_);
138 int old = shared_value_;
139
140 // Use a loop to increase the chance of race.
141 for (int i = 0; i < kOperationsToRun; ++i) {
142 ++shared_value_;
143 }
144 EXPECT_EQ(old + kOperationsToRun, shared_value_);
145 shared_value_ = 0;
146
147 lock_.Unlock();
148
149 AfterEnd();
150 }
151
152 private:
153 Lock lock_;
154};
155
156template <class Op, class Verifier>
157class AtomicOpRunner : public RunnerBase {
158 public:
159 explicit AtomicOpRunner(int initial_value) : RunnerBase(initial_value) {}
160
161 void OnMessage(Message* msg) override {
162 BeforeStart();
163
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164 std::vector<int> values;
165 values.reserve(kOperationsToRun);
166
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700167 // Generate a bunch of values by updating shared_value_ atomically.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000168 for (int i = 0; i < kOperationsToRun; ++i) {
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700169 values.push_back(Op::AtomicOp(&shared_value_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 }
171
Yves Gerey665174f2018-06-19 15:03:05 +0200172 { // Add them all to the set.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173 CritScope cs(&all_values_crit_);
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700174 verifier_.Verify(values);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 }
176
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700177 if (AfterEnd()) {
178 verifier_.Finalize();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179 }
180 }
181
182 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183 CriticalSection all_values_crit_;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700184 Verifier verifier_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185};
186
187struct IncrementOp {
188 static int AtomicOp(int* i) { return AtomicOps::Increment(i); }
189};
190
191struct DecrementOp {
192 static int AtomicOp(int* i) { return AtomicOps::Decrement(i); }
193};
194
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700195struct CompareAndSwapOp {
196 static int AtomicOp(int* i) { return AtomicOps::CompareAndSwap(i, 0, 1); }
197};
198
nisseb9c2f7c2017-04-20 02:23:08 -0700199void StartThreads(std::vector<std::unique_ptr<Thread>>* threads,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200 MessageHandler* handler) {
201 for (int i = 0; i < kNumThreads; ++i) {
tommie7251592017-07-14 14:44:46 -0700202 std::unique_ptr<Thread> thread(Thread::Create());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000203 thread->Start();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700204 thread->Post(RTC_FROM_HERE, handler);
nisseb9c2f7c2017-04-20 02:23:08 -0700205 threads->push_back(std::move(thread));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000206 }
207}
208
209} // namespace
210
211TEST(AtomicOpsTest, Simple) {
212 int value = 0;
213 EXPECT_EQ(1, AtomicOps::Increment(&value));
214 EXPECT_EQ(1, value);
215 EXPECT_EQ(2, AtomicOps::Increment(&value));
216 EXPECT_EQ(2, value);
217 EXPECT_EQ(1, AtomicOps::Decrement(&value));
218 EXPECT_EQ(1, value);
219 EXPECT_EQ(0, AtomicOps::Decrement(&value));
220 EXPECT_EQ(0, value);
221}
222
Peter Boström455a2522015-12-18 17:00:25 +0100223TEST(AtomicOpsTest, SimplePtr) {
224 class Foo {};
225 Foo* volatile foo = nullptr;
jbauch555604a2016-04-26 03:13:22 -0700226 std::unique_ptr<Foo> a(new Foo());
227 std::unique_ptr<Foo> b(new Foo());
Peter Boström455a2522015-12-18 17:00:25 +0100228 // Reading the initial value should work as expected.
229 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == nullptr);
230 // Setting using compare and swap should work.
231 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
232 &foo, static_cast<Foo*>(nullptr), a.get()) == nullptr);
233 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
234 // Setting another value but with the wrong previous pointer should fail
235 // (remain a).
236 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
237 &foo, static_cast<Foo*>(nullptr), b.get()) == a.get());
238 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
239 // Replacing a with b should work.
240 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(&foo, a.get(), b.get()) ==
241 a.get());
242 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == b.get());
243}
244
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000245TEST(AtomicOpsTest, Increment) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246 // Create and start lots of threads.
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700247 AtomicOpRunner<IncrementOp, UniqueValueVerifier> runner(0);
nisseb9c2f7c2017-04-20 02:23:08 -0700248 std::vector<std::unique_ptr<Thread>> threads;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 StartThreads(&threads, &runner);
250 runner.SetExpectedThreadCount(kNumThreads);
251
252 // Release the hounds!
253 EXPECT_TRUE(runner.Run());
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700254 EXPECT_EQ(kOperationsToRun * kNumThreads, runner.shared_value());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255}
256
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000257TEST(AtomicOpsTest, Decrement) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258 // Create and start lots of threads.
Yves Gerey665174f2018-06-19 15:03:05 +0200259 AtomicOpRunner<DecrementOp, UniqueValueVerifier> runner(kOperationsToRun *
260 kNumThreads);
nisseb9c2f7c2017-04-20 02:23:08 -0700261 std::vector<std::unique_ptr<Thread>> threads;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 StartThreads(&threads, &runner);
263 runner.SetExpectedThreadCount(kNumThreads);
264
265 // Release the hounds!
266 EXPECT_TRUE(runner.Run());
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700267 EXPECT_EQ(0, runner.shared_value());
268}
269
270TEST(AtomicOpsTest, CompareAndSwap) {
271 // Create and start lots of threads.
272 AtomicOpRunner<CompareAndSwapOp, CompareAndSwapVerifier> runner(0);
nisseb9c2f7c2017-04-20 02:23:08 -0700273 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700274 StartThreads(&threads, &runner);
275 runner.SetExpectedThreadCount(kNumThreads);
276
277 // Release the hounds!
278 EXPECT_TRUE(runner.Run());
279 EXPECT_EQ(1, runner.shared_value());
280}
281
282TEST(GlobalLockTest, Basic) {
283 // Create and start lots of threads.
284 LockRunner<GlobalLock> runner;
nisseb9c2f7c2017-04-20 02:23:08 -0700285 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700286 StartThreads(&threads, &runner);
287 runner.SetExpectedThreadCount(kNumThreads);
288
289 // Release the hounds!
290 EXPECT_TRUE(runner.Run());
291 EXPECT_EQ(0, runner.shared_value());
292}
293
294TEST(CriticalSectionTest, Basic) {
295 // Create and start lots of threads.
296 LockRunner<CriticalSectionLock> runner;
nisseb9c2f7c2017-04-20 02:23:08 -0700297 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700298 StartThreads(&threads, &runner);
299 runner.SetExpectedThreadCount(kNumThreads);
300
301 // Release the hounds!
302 EXPECT_TRUE(runner.Run());
303 EXPECT_EQ(0, runner.shared_value());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000304}
305
tommied281e92016-01-21 23:47:25 -0800306class PerfTestData {
307 public:
308 PerfTestData(int expected_count, Event* event)
Yves Gerey665174f2018-06-19 15:03:05 +0200309 : cache_line_barrier_1_(),
310 cache_line_barrier_2_(),
311 expected_count_(expected_count),
312 event_(event) {
tommied281e92016-01-21 23:47:25 -0800313 cache_line_barrier_1_[0]++; // Avoid 'is not used'.
314 cache_line_barrier_2_[0]++; // Avoid 'is not used'.
315 }
316 ~PerfTestData() {}
317
318 void AddToCounter(int add) {
319 rtc::CritScope cs(&lock_);
320 my_counter_ += add;
321 if (my_counter_ == expected_count_)
322 event_->Set();
323 }
324
325 int64_t total() const {
326 // Assume that only one thread is running now.
327 return my_counter_;
328 }
329
330 private:
331 uint8_t cache_line_barrier_1_[64];
332 CriticalSection lock_;
333 uint8_t cache_line_barrier_2_[64];
334 int64_t my_counter_ = 0;
335 const int expected_count_;
336 Event* const event_;
337};
338
339class PerfTestThread {
340 public:
341 PerfTestThread() : thread_(&ThreadFunc, this, "CsPerf") {}
342
343 void Start(PerfTestData* data, int repeats, int id) {
344 RTC_DCHECK(!thread_.IsRunning());
345 RTC_DCHECK(!data_);
346 data_ = data;
347 repeats_ = repeats;
348 my_id_ = id;
349 thread_.Start();
350 }
351
352 void Stop() {
353 RTC_DCHECK(thread_.IsRunning());
354 RTC_DCHECK(data_);
355 thread_.Stop();
356 repeats_ = 0;
357 data_ = nullptr;
358 my_id_ = 0;
359 }
360
361 private:
362 static bool ThreadFunc(void* param) {
363 PerfTestThread* me = static_cast<PerfTestThread*>(param);
364 for (int i = 0; i < me->repeats_; ++i)
365 me->data_->AddToCounter(me->my_id_);
366 return false;
367 }
368
369 PlatformThread thread_;
370 PerfTestData* data_ = nullptr;
371 int repeats_ = 0;
372 int my_id_ = 0;
373};
374
375// Comparison of output of this test as tested on a MacBook Pro Retina, 15-inch,
376// Mid 2014, 2,8 GHz Intel Core i7, 16 GB 1600 MHz DDR3,
377// running OS X El Capitan, 10.11.2.
378//
379// Native mutex implementation:
380// Approximate CPU usage:
381// System: ~16%
382// User mode: ~1.3%
383// Idle: ~82%
384// Unit test output:
385// [ OK ] CriticalSectionTest.Performance (234545 ms)
386//
387// Special partially spin lock based implementation:
388// Approximate CPU usage:
389// System: ~75%
390// User mode: ~16%
391// Idle: ~8%
392// Unit test output:
393// [ OK ] CriticalSectionTest.Performance (2107 ms)
394//
395// The test is disabled by default to avoid unecessarily loading the bots.
396TEST(CriticalSectionTest, DISABLED_Performance) {
397 PerfTestThread threads[8];
Niels Möllerc572ff32018-11-07 08:43:50 +0100398 Event event;
tommied281e92016-01-21 23:47:25 -0800399
400 static const int kThreadRepeats = 10000000;
401 static const int kExpectedCount = kThreadRepeats * arraysize(threads);
402 PerfTestData test_data(kExpectedCount, &event);
403
404 for (auto& t : threads)
405 t.Start(&test_data, kThreadRepeats, 1);
406
407 event.Wait(Event::kForever);
408
409 for (auto& t : threads)
410 t.Stop();
411}
412
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000413} // namespace rtc