blob: 04af94995b370dac7985a52cda12bffc7755f008 [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
Jonas Olssona4d87372019-07-05 19:08:33 +020011#include "rtc_base/critical_section.h"
12
Yves Gerey3e707812018-11-28 16:47:49 +010013#include <stddef.h>
14#include <stdint.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020015
jbauch555604a2016-04-26 03:13:22 -070016#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017#include <set>
Yves Gerey3e707812018-11-28 16:47:49 +010018#include <utility>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#include <vector>
20
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/arraysize.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/checks.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "rtc_base/event.h"
Yves Gerey3e707812018-11-28 16:47:49 +010025#include "rtc_base/location.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/message_handler.h"
27#include "rtc_base/message_queue.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/platform_thread.h"
29#include "rtc_base/thread.h"
Yves Gerey3e707812018-11-28 16:47:49 +010030#include "test/gtest.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031
32namespace rtc {
33
34namespace {
35
36const int kLongTime = 10000; // 10 seconds
37const int kNumThreads = 16;
38const int kOperationsToRun = 1000;
39
Jiayang Liubef8d2d2015-03-26 14:38:46 -070040class UniqueValueVerifier {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041 public:
Jiayang Liubef8d2d2015-03-26 14:38:46 -070042 void Verify(const std::vector<int>& values) {
43 for (size_t i = 0; i < values.size(); ++i) {
44 std::pair<std::set<int>::iterator, bool> result =
45 all_values_.insert(values[i]);
46 // Each value should only be taken by one thread, so if this value
47 // has already been added, something went wrong.
48 EXPECT_TRUE(result.second)
49 << " Thread=" << Thread::Current() << " value=" << values[i];
50 }
51 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052
Jiayang Liubef8d2d2015-03-26 14:38:46 -070053 void Finalize() {}
54
55 private:
56 std::set<int> all_values_;
57};
58
59class CompareAndSwapVerifier {
60 public:
61 CompareAndSwapVerifier() : zero_count_(0) {}
62
63 void Verify(const std::vector<int>& values) {
64 for (auto v : values) {
65 if (v == 0) {
66 EXPECT_EQ(0, zero_count_) << "Thread=" << Thread::Current();
67 ++zero_count_;
68 } else {
69 EXPECT_EQ(1, v) << " Thread=" << Thread::Current();
70 }
71 }
72 }
73
Yves Gerey665174f2018-06-19 15:03:05 +020074 void Finalize() { EXPECT_EQ(1, zero_count_); }
75
Jiayang Liubef8d2d2015-03-26 14:38:46 -070076 private:
77 int zero_count_;
78};
79
80class RunnerBase : public MessageHandler {
81 public:
82 explicit RunnerBase(int value)
83 : threads_active_(0),
84 start_event_(true, false),
85 done_event_(true, false),
86 shared_value_(value) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087
88 bool Run() {
89 // Signal all threads to start.
90 start_event_.Set();
91
92 // Wait for all threads to finish.
93 return done_event_.Wait(kLongTime);
94 }
95
Yves Gerey665174f2018-06-19 15:03:05 +020096 void SetExpectedThreadCount(int count) { threads_active_ = count; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000097
Jiayang Liubef8d2d2015-03-26 14:38:46 -070098 int shared_value() const { return shared_value_; }
99
100 protected:
101 // Derived classes must override OnMessage, and call BeforeStart and AfterEnd
102 // at the beginning and the end of OnMessage respectively.
Yves Gerey665174f2018-06-19 15:03:05 +0200103 void BeforeStart() { ASSERT_TRUE(start_event_.Wait(kLongTime)); }
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700104
105 // Returns true if all threads have finished.
106 bool AfterEnd() {
107 if (AtomicOps::Decrement(&threads_active_) == 0) {
108 done_event_.Set();
109 return true;
110 }
111 return false;
112 }
113
114 int threads_active_;
115 Event start_event_;
116 Event done_event_;
117 int shared_value_;
118};
119
danilchap3c6abd22017-09-06 05:46:29 -0700120class RTC_LOCKABLE CriticalSectionLock {
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700121 public:
danilchap3c6abd22017-09-06 05:46:29 -0700122 void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { cs_.Enter(); }
123 void Unlock() RTC_UNLOCK_FUNCTION() { cs_.Leave(); }
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700124
125 private:
126 CriticalSection cs_;
127};
128
129template <class Lock>
130class LockRunner : public RunnerBase {
131 public:
132 LockRunner() : RunnerBase(0) {}
133
134 void OnMessage(Message* msg) override {
135 BeforeStart();
136
137 lock_.Lock();
138
139 EXPECT_EQ(0, shared_value_);
140 int old = shared_value_;
141
142 // Use a loop to increase the chance of race.
143 for (int i = 0; i < kOperationsToRun; ++i) {
144 ++shared_value_;
145 }
146 EXPECT_EQ(old + kOperationsToRun, shared_value_);
147 shared_value_ = 0;
148
149 lock_.Unlock();
150
151 AfterEnd();
152 }
153
154 private:
155 Lock lock_;
156};
157
158template <class Op, class Verifier>
159class AtomicOpRunner : public RunnerBase {
160 public:
161 explicit AtomicOpRunner(int initial_value) : RunnerBase(initial_value) {}
162
163 void OnMessage(Message* msg) override {
164 BeforeStart();
165
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166 std::vector<int> values;
167 values.reserve(kOperationsToRun);
168
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700169 // Generate a bunch of values by updating shared_value_ atomically.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 for (int i = 0; i < kOperationsToRun; ++i) {
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700171 values.push_back(Op::AtomicOp(&shared_value_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172 }
173
Yves Gerey665174f2018-06-19 15:03:05 +0200174 { // Add them all to the set.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 CritScope cs(&all_values_crit_);
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700176 verifier_.Verify(values);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177 }
178
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700179 if (AfterEnd()) {
180 verifier_.Finalize();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181 }
182 }
183
184 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 CriticalSection all_values_crit_;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700186 Verifier verifier_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187};
188
189struct IncrementOp {
190 static int AtomicOp(int* i) { return AtomicOps::Increment(i); }
191};
192
193struct DecrementOp {
194 static int AtomicOp(int* i) { return AtomicOps::Decrement(i); }
195};
196
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700197struct CompareAndSwapOp {
198 static int AtomicOp(int* i) { return AtomicOps::CompareAndSwap(i, 0, 1); }
199};
200
nisseb9c2f7c2017-04-20 02:23:08 -0700201void StartThreads(std::vector<std::unique_ptr<Thread>>* threads,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000202 MessageHandler* handler) {
203 for (int i = 0; i < kNumThreads; ++i) {
tommie7251592017-07-14 14:44:46 -0700204 std::unique_ptr<Thread> thread(Thread::Create());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205 thread->Start();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700206 thread->Post(RTC_FROM_HERE, handler);
nisseb9c2f7c2017-04-20 02:23:08 -0700207 threads->push_back(std::move(thread));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000208 }
209}
210
211} // namespace
212
213TEST(AtomicOpsTest, Simple) {
214 int value = 0;
215 EXPECT_EQ(1, AtomicOps::Increment(&value));
216 EXPECT_EQ(1, value);
217 EXPECT_EQ(2, AtomicOps::Increment(&value));
218 EXPECT_EQ(2, value);
219 EXPECT_EQ(1, AtomicOps::Decrement(&value));
220 EXPECT_EQ(1, value);
221 EXPECT_EQ(0, AtomicOps::Decrement(&value));
222 EXPECT_EQ(0, value);
223}
224
Peter Boström455a2522015-12-18 17:00:25 +0100225TEST(AtomicOpsTest, SimplePtr) {
226 class Foo {};
227 Foo* volatile foo = nullptr;
jbauch555604a2016-04-26 03:13:22 -0700228 std::unique_ptr<Foo> a(new Foo());
229 std::unique_ptr<Foo> b(new Foo());
Peter Boström455a2522015-12-18 17:00:25 +0100230 // Reading the initial value should work as expected.
231 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == nullptr);
232 // Setting using compare and swap should work.
233 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
234 &foo, static_cast<Foo*>(nullptr), a.get()) == nullptr);
235 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
236 // Setting another value but with the wrong previous pointer should fail
237 // (remain a).
238 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
239 &foo, static_cast<Foo*>(nullptr), b.get()) == a.get());
240 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
241 // Replacing a with b should work.
242 EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(&foo, a.get(), b.get()) ==
243 a.get());
244 EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == b.get());
245}
246
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000247TEST(AtomicOpsTest, Increment) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000248 // Create and start lots of threads.
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700249 AtomicOpRunner<IncrementOp, UniqueValueVerifier> runner(0);
nisseb9c2f7c2017-04-20 02:23:08 -0700250 std::vector<std::unique_ptr<Thread>> threads;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251 StartThreads(&threads, &runner);
252 runner.SetExpectedThreadCount(kNumThreads);
253
254 // Release the hounds!
255 EXPECT_TRUE(runner.Run());
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700256 EXPECT_EQ(kOperationsToRun * kNumThreads, runner.shared_value());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000257}
258
henrike@webrtc.orgc732a3e2014-10-09 22:08:15 +0000259TEST(AtomicOpsTest, Decrement) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260 // Create and start lots of threads.
Yves Gerey665174f2018-06-19 15:03:05 +0200261 AtomicOpRunner<DecrementOp, UniqueValueVerifier> runner(kOperationsToRun *
262 kNumThreads);
nisseb9c2f7c2017-04-20 02:23:08 -0700263 std::vector<std::unique_ptr<Thread>> threads;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 StartThreads(&threads, &runner);
265 runner.SetExpectedThreadCount(kNumThreads);
266
267 // Release the hounds!
268 EXPECT_TRUE(runner.Run());
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700269 EXPECT_EQ(0, runner.shared_value());
270}
271
272TEST(AtomicOpsTest, CompareAndSwap) {
273 // Create and start lots of threads.
274 AtomicOpRunner<CompareAndSwapOp, CompareAndSwapVerifier> runner(0);
nisseb9c2f7c2017-04-20 02:23:08 -0700275 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700276 StartThreads(&threads, &runner);
277 runner.SetExpectedThreadCount(kNumThreads);
278
279 // Release the hounds!
280 EXPECT_TRUE(runner.Run());
281 EXPECT_EQ(1, runner.shared_value());
282}
283
284TEST(GlobalLockTest, Basic) {
285 // Create and start lots of threads.
286 LockRunner<GlobalLock> runner;
nisseb9c2f7c2017-04-20 02:23:08 -0700287 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700288 StartThreads(&threads, &runner);
289 runner.SetExpectedThreadCount(kNumThreads);
290
291 // Release the hounds!
292 EXPECT_TRUE(runner.Run());
293 EXPECT_EQ(0, runner.shared_value());
294}
295
296TEST(CriticalSectionTest, Basic) {
297 // Create and start lots of threads.
298 LockRunner<CriticalSectionLock> runner;
nisseb9c2f7c2017-04-20 02:23:08 -0700299 std::vector<std::unique_ptr<Thread>> threads;
Jiayang Liubef8d2d2015-03-26 14:38:46 -0700300 StartThreads(&threads, &runner);
301 runner.SetExpectedThreadCount(kNumThreads);
302
303 // Release the hounds!
304 EXPECT_TRUE(runner.Run());
305 EXPECT_EQ(0, runner.shared_value());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306}
307
tommied281e92016-01-21 23:47:25 -0800308class PerfTestData {
309 public:
310 PerfTestData(int expected_count, Event* event)
Yves Gerey665174f2018-06-19 15:03:05 +0200311 : cache_line_barrier_1_(),
312 cache_line_barrier_2_(),
313 expected_count_(expected_count),
314 event_(event) {
tommied281e92016-01-21 23:47:25 -0800315 cache_line_barrier_1_[0]++; // Avoid 'is not used'.
316 cache_line_barrier_2_[0]++; // Avoid 'is not used'.
317 }
318 ~PerfTestData() {}
319
320 void AddToCounter(int add) {
321 rtc::CritScope cs(&lock_);
322 my_counter_ += add;
323 if (my_counter_ == expected_count_)
324 event_->Set();
325 }
326
327 int64_t total() const {
328 // Assume that only one thread is running now.
329 return my_counter_;
330 }
331
332 private:
333 uint8_t cache_line_barrier_1_[64];
334 CriticalSection lock_;
335 uint8_t cache_line_barrier_2_[64];
336 int64_t my_counter_ = 0;
337 const int expected_count_;
338 Event* const event_;
339};
340
341class PerfTestThread {
342 public:
343 PerfTestThread() : thread_(&ThreadFunc, this, "CsPerf") {}
344
345 void Start(PerfTestData* data, int repeats, int id) {
346 RTC_DCHECK(!thread_.IsRunning());
347 RTC_DCHECK(!data_);
348 data_ = data;
349 repeats_ = repeats;
350 my_id_ = id;
351 thread_.Start();
352 }
353
354 void Stop() {
355 RTC_DCHECK(thread_.IsRunning());
356 RTC_DCHECK(data_);
357 thread_.Stop();
358 repeats_ = 0;
359 data_ = nullptr;
360 my_id_ = 0;
361 }
362
363 private:
Niels Möller4731f002019-05-03 09:34:24 +0200364 static void ThreadFunc(void* param) {
tommied281e92016-01-21 23:47:25 -0800365 PerfTestThread* me = static_cast<PerfTestThread*>(param);
366 for (int i = 0; i < me->repeats_; ++i)
367 me->data_->AddToCounter(me->my_id_);
tommied281e92016-01-21 23:47:25 -0800368 }
369
370 PlatformThread thread_;
371 PerfTestData* data_ = nullptr;
372 int repeats_ = 0;
373 int my_id_ = 0;
374};
375
Oskar Sundbom13471a42019-03-01 16:11:49 +0100376// Comparison of output of this test as tested on a MacBook Pro, 13-inch,
377// 2017, 3,5 GHz Intel Core i7, 16 GB 2133 MHz LPDDR3,
378// running macOS Mojave, 10.14.3.
tommied281e92016-01-21 23:47:25 -0800379//
Oskar Sundbom13471a42019-03-01 16:11:49 +0100380// Native mutex implementation using fair policy (previously macOS default):
tommied281e92016-01-21 23:47:25 -0800381// Approximate CPU usage:
Oskar Sundbom13471a42019-03-01 16:11:49 +0100382// real 4m54.612s
383// user 1m20.575s
384// sys 3m48.872s
tommied281e92016-01-21 23:47:25 -0800385// Unit test output:
Oskar Sundbom13471a42019-03-01 16:11:49 +0100386// [ OK ] CriticalSectionTest.Performance (294375 ms)
387//
388// Native mutex implementation using first fit policy (current macOS default):
389// Approximate CPU usage:
390// real 0m11.535s
391// user 0m12.738s
392// sys 0m31.207s
393// Unit test output:
394// [ OK ] CriticalSectionTest.Performance (11444 ms)
tommied281e92016-01-21 23:47:25 -0800395//
396// Special partially spin lock based implementation:
397// Approximate CPU usage:
Oskar Sundbom13471a42019-03-01 16:11:49 +0100398// real 0m2.113s
399// user 0m3.014s
400// sys 0m4.495s
tommied281e92016-01-21 23:47:25 -0800401// Unit test output:
Oskar Sundbom13471a42019-03-01 16:11:49 +0100402// [ OK ] CriticalSectionTest.Performance (1885 ms)
tommied281e92016-01-21 23:47:25 -0800403//
404// The test is disabled by default to avoid unecessarily loading the bots.
405TEST(CriticalSectionTest, DISABLED_Performance) {
406 PerfTestThread threads[8];
Niels Möllerc572ff32018-11-07 08:43:50 +0100407 Event event;
tommied281e92016-01-21 23:47:25 -0800408
409 static const int kThreadRepeats = 10000000;
410 static const int kExpectedCount = kThreadRepeats * arraysize(threads);
411 PerfTestData test_data(kExpectedCount, &event);
412
413 for (auto& t : threads)
414 t.Start(&test_data, kThreadRepeats, 1);
415
416 event.Wait(Event::kForever);
417
418 for (auto& t : threads)
419 t.Stop();
420}
421
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000422} // namespace rtc