You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

431 lines
11 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #include "rtc_base/critical_section.h"
  11. #include <stddef.h>
  12. #include <stdint.h>
  13. #include <memory>
  14. #include <set>
  15. #include <type_traits>
  16. #include <utility>
  17. #include <vector>
  18. #include "absl/base/attributes.h"
  19. #include "rtc_base/arraysize.h"
  20. #include "rtc_base/atomic_ops.h"
  21. #include "rtc_base/checks.h"
  22. #include "rtc_base/event.h"
  23. #include "rtc_base/location.h"
  24. #include "rtc_base/message_handler.h"
  25. #include "rtc_base/message_queue.h"
  26. #include "rtc_base/platform_thread.h"
  27. #include "rtc_base/thread.h"
  28. #include "test/gtest.h"
  29. namespace rtc {
  30. namespace {
  31. const int kLongTime = 10000; // 10 seconds
  32. const int kNumThreads = 16;
  33. const int kOperationsToRun = 1000;
  34. class UniqueValueVerifier {
  35. public:
  36. void Verify(const std::vector<int>& values) {
  37. for (size_t i = 0; i < values.size(); ++i) {
  38. std::pair<std::set<int>::iterator, bool> result =
  39. all_values_.insert(values[i]);
  40. // Each value should only be taken by one thread, so if this value
  41. // has already been added, something went wrong.
  42. EXPECT_TRUE(result.second)
  43. << " Thread=" << Thread::Current() << " value=" << values[i];
  44. }
  45. }
  46. void Finalize() {}
  47. private:
  48. std::set<int> all_values_;
  49. };
  50. class CompareAndSwapVerifier {
  51. public:
  52. CompareAndSwapVerifier() : zero_count_(0) {}
  53. void Verify(const std::vector<int>& values) {
  54. for (auto v : values) {
  55. if (v == 0) {
  56. EXPECT_EQ(0, zero_count_) << "Thread=" << Thread::Current();
  57. ++zero_count_;
  58. } else {
  59. EXPECT_EQ(1, v) << " Thread=" << Thread::Current();
  60. }
  61. }
  62. }
  63. void Finalize() { EXPECT_EQ(1, zero_count_); }
  64. private:
  65. int zero_count_;
  66. };
  67. class RunnerBase : public MessageHandler {
  68. public:
  69. explicit RunnerBase(int value)
  70. : threads_active_(0),
  71. start_event_(true, false),
  72. done_event_(true, false),
  73. shared_value_(value) {}
  74. bool Run() {
  75. // Signal all threads to start.
  76. start_event_.Set();
  77. // Wait for all threads to finish.
  78. return done_event_.Wait(kLongTime);
  79. }
  80. void SetExpectedThreadCount(int count) { threads_active_ = count; }
  81. int shared_value() const { return shared_value_; }
  82. protected:
  83. // Derived classes must override OnMessage, and call BeforeStart and AfterEnd
  84. // at the beginning and the end of OnMessage respectively.
  85. void BeforeStart() { ASSERT_TRUE(start_event_.Wait(kLongTime)); }
  86. // Returns true if all threads have finished.
  87. bool AfterEnd() {
  88. if (AtomicOps::Decrement(&threads_active_) == 0) {
  89. done_event_.Set();
  90. return true;
  91. }
  92. return false;
  93. }
  94. int threads_active_;
  95. Event start_event_;
  96. Event done_event_;
  97. int shared_value_;
  98. };
  99. class RTC_LOCKABLE CriticalSectionLock {
  100. public:
  101. void Lock() RTC_EXCLUSIVE_LOCK_FUNCTION() { cs_.Enter(); }
  102. void Unlock() RTC_UNLOCK_FUNCTION() { cs_.Leave(); }
  103. private:
  104. CriticalSection cs_;
  105. };
  106. template <class Lock>
  107. class LockRunner : public RunnerBase {
  108. public:
  109. LockRunner() : RunnerBase(0) {}
  110. void OnMessage(Message* msg) override {
  111. BeforeStart();
  112. lock_.Lock();
  113. EXPECT_EQ(0, shared_value_);
  114. int old = shared_value_;
  115. // Use a loop to increase the chance of race.
  116. for (int i = 0; i < kOperationsToRun; ++i) {
  117. ++shared_value_;
  118. }
  119. EXPECT_EQ(old + kOperationsToRun, shared_value_);
  120. shared_value_ = 0;
  121. lock_.Unlock();
  122. AfterEnd();
  123. }
  124. private:
  125. Lock lock_;
  126. };
  127. template <class Op, class Verifier>
  128. class AtomicOpRunner : public RunnerBase {
  129. public:
  130. explicit AtomicOpRunner(int initial_value) : RunnerBase(initial_value) {}
  131. void OnMessage(Message* msg) override {
  132. BeforeStart();
  133. std::vector<int> values;
  134. values.reserve(kOperationsToRun);
  135. // Generate a bunch of values by updating shared_value_ atomically.
  136. for (int i = 0; i < kOperationsToRun; ++i) {
  137. values.push_back(Op::AtomicOp(&shared_value_));
  138. }
  139. { // Add them all to the set.
  140. CritScope cs(&all_values_crit_);
  141. verifier_.Verify(values);
  142. }
  143. if (AfterEnd()) {
  144. verifier_.Finalize();
  145. }
  146. }
  147. private:
  148. CriticalSection all_values_crit_;
  149. Verifier verifier_;
  150. };
  151. struct IncrementOp {
  152. static int AtomicOp(int* i) { return AtomicOps::Increment(i); }
  153. };
  154. struct DecrementOp {
  155. static int AtomicOp(int* i) { return AtomicOps::Decrement(i); }
  156. };
  157. struct CompareAndSwapOp {
  158. static int AtomicOp(int* i) { return AtomicOps::CompareAndSwap(i, 0, 1); }
  159. };
  160. void StartThreads(std::vector<std::unique_ptr<Thread>>* threads,
  161. MessageHandler* handler) {
  162. for (int i = 0; i < kNumThreads; ++i) {
  163. std::unique_ptr<Thread> thread(Thread::Create());
  164. thread->Start();
  165. thread->Post(RTC_FROM_HERE, handler);
  166. threads->push_back(std::move(thread));
  167. }
  168. }
  169. } // namespace
  170. TEST(AtomicOpsTest, Simple) {
  171. int value = 0;
  172. EXPECT_EQ(1, AtomicOps::Increment(&value));
  173. EXPECT_EQ(1, value);
  174. EXPECT_EQ(2, AtomicOps::Increment(&value));
  175. EXPECT_EQ(2, value);
  176. EXPECT_EQ(1, AtomicOps::Decrement(&value));
  177. EXPECT_EQ(1, value);
  178. EXPECT_EQ(0, AtomicOps::Decrement(&value));
  179. EXPECT_EQ(0, value);
  180. }
  181. TEST(AtomicOpsTest, SimplePtr) {
  182. class Foo {};
  183. Foo* volatile foo = nullptr;
  184. std::unique_ptr<Foo> a(new Foo());
  185. std::unique_ptr<Foo> b(new Foo());
  186. // Reading the initial value should work as expected.
  187. EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == nullptr);
  188. // Setting using compare and swap should work.
  189. EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
  190. &foo, static_cast<Foo*>(nullptr), a.get()) == nullptr);
  191. EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
  192. // Setting another value but with the wrong previous pointer should fail
  193. // (remain a).
  194. EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(
  195. &foo, static_cast<Foo*>(nullptr), b.get()) == a.get());
  196. EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == a.get());
  197. // Replacing a with b should work.
  198. EXPECT_TRUE(rtc::AtomicOps::CompareAndSwapPtr(&foo, a.get(), b.get()) ==
  199. a.get());
  200. EXPECT_TRUE(rtc::AtomicOps::AcquireLoadPtr(&foo) == b.get());
  201. }
  202. TEST(AtomicOpsTest, Increment) {
  203. // Create and start lots of threads.
  204. AtomicOpRunner<IncrementOp, UniqueValueVerifier> runner(0);
  205. std::vector<std::unique_ptr<Thread>> threads;
  206. StartThreads(&threads, &runner);
  207. runner.SetExpectedThreadCount(kNumThreads);
  208. // Release the hounds!
  209. EXPECT_TRUE(runner.Run());
  210. EXPECT_EQ(kOperationsToRun * kNumThreads, runner.shared_value());
  211. }
  212. TEST(AtomicOpsTest, Decrement) {
  213. // Create and start lots of threads.
  214. AtomicOpRunner<DecrementOp, UniqueValueVerifier> runner(kOperationsToRun *
  215. kNumThreads);
  216. std::vector<std::unique_ptr<Thread>> threads;
  217. StartThreads(&threads, &runner);
  218. runner.SetExpectedThreadCount(kNumThreads);
  219. // Release the hounds!
  220. EXPECT_TRUE(runner.Run());
  221. EXPECT_EQ(0, runner.shared_value());
  222. }
  223. TEST(AtomicOpsTest, CompareAndSwap) {
  224. // Create and start lots of threads.
  225. AtomicOpRunner<CompareAndSwapOp, CompareAndSwapVerifier> runner(0);
  226. std::vector<std::unique_ptr<Thread>> threads;
  227. StartThreads(&threads, &runner);
  228. runner.SetExpectedThreadCount(kNumThreads);
  229. // Release the hounds!
  230. EXPECT_TRUE(runner.Run());
  231. EXPECT_EQ(1, runner.shared_value());
  232. }
  233. TEST(GlobalLockTest, CanHaveStaticStorageDuration) {
  234. static_assert(std::is_trivially_destructible<GlobalLock>::value, "");
  235. ABSL_CONST_INIT static GlobalLock global_lock;
  236. global_lock.Lock();
  237. global_lock.Unlock();
  238. }
  239. TEST(GlobalLockTest, Basic) {
  240. // Create and start lots of threads.
  241. LockRunner<GlobalLock> runner;
  242. std::vector<std::unique_ptr<Thread>> threads;
  243. StartThreads(&threads, &runner);
  244. runner.SetExpectedThreadCount(kNumThreads);
  245. // Release the hounds!
  246. EXPECT_TRUE(runner.Run());
  247. EXPECT_EQ(0, runner.shared_value());
  248. }
  249. TEST(CriticalSectionTest, Basic) {
  250. // Create and start lots of threads.
  251. LockRunner<CriticalSectionLock> runner;
  252. std::vector<std::unique_ptr<Thread>> threads;
  253. StartThreads(&threads, &runner);
  254. runner.SetExpectedThreadCount(kNumThreads);
  255. // Release the hounds!
  256. EXPECT_TRUE(runner.Run());
  257. EXPECT_EQ(0, runner.shared_value());
  258. }
  259. class PerfTestData {
  260. public:
  261. PerfTestData(int expected_count, Event* event)
  262. : cache_line_barrier_1_(),
  263. cache_line_barrier_2_(),
  264. expected_count_(expected_count),
  265. event_(event) {
  266. cache_line_barrier_1_[0]++; // Avoid 'is not used'.
  267. cache_line_barrier_2_[0]++; // Avoid 'is not used'.
  268. }
  269. ~PerfTestData() {}
  270. void AddToCounter(int add) {
  271. rtc::CritScope cs(&lock_);
  272. my_counter_ += add;
  273. if (my_counter_ == expected_count_)
  274. event_->Set();
  275. }
  276. int64_t total() const {
  277. // Assume that only one thread is running now.
  278. return my_counter_;
  279. }
  280. private:
  281. uint8_t cache_line_barrier_1_[64];
  282. CriticalSection lock_;
  283. uint8_t cache_line_barrier_2_[64];
  284. int64_t my_counter_ = 0;
  285. const int expected_count_;
  286. Event* const event_;
  287. };
  288. class PerfTestThread {
  289. public:
  290. PerfTestThread() : thread_(&ThreadFunc, this, "CsPerf") {}
  291. void Start(PerfTestData* data, int repeats, int id) {
  292. RTC_DCHECK(!thread_.IsRunning());
  293. RTC_DCHECK(!data_);
  294. data_ = data;
  295. repeats_ = repeats;
  296. my_id_ = id;
  297. thread_.Start();
  298. }
  299. void Stop() {
  300. RTC_DCHECK(thread_.IsRunning());
  301. RTC_DCHECK(data_);
  302. thread_.Stop();
  303. repeats_ = 0;
  304. data_ = nullptr;
  305. my_id_ = 0;
  306. }
  307. private:
  308. static void ThreadFunc(void* param) {
  309. PerfTestThread* me = static_cast<PerfTestThread*>(param);
  310. for (int i = 0; i < me->repeats_; ++i)
  311. me->data_->AddToCounter(me->my_id_);
  312. }
  313. PlatformThread thread_;
  314. PerfTestData* data_ = nullptr;
  315. int repeats_ = 0;
  316. int my_id_ = 0;
  317. };
  318. // Comparison of output of this test as tested on a MacBook Pro, 13-inch,
  319. // 2017, 3,5 GHz Intel Core i7, 16 GB 2133 MHz LPDDR3,
  320. // running macOS Mojave, 10.14.3.
  321. //
  322. // Native mutex implementation using fair policy (previously macOS default):
  323. // Approximate CPU usage:
  324. // real 4m54.612s
  325. // user 1m20.575s
  326. // sys 3m48.872s
  327. // Unit test output:
  328. // [ OK ] CriticalSectionTest.Performance (294375 ms)
  329. //
  330. // Native mutex implementation using first fit policy (current macOS default):
  331. // Approximate CPU usage:
  332. // real 0m11.535s
  333. // user 0m12.738s
  334. // sys 0m31.207s
  335. // Unit test output:
  336. // [ OK ] CriticalSectionTest.Performance (11444 ms)
  337. //
  338. // Special partially spin lock based implementation:
  339. // Approximate CPU usage:
  340. // real 0m2.113s
  341. // user 0m3.014s
  342. // sys 0m4.495s
  343. // Unit test output:
  344. // [ OK ] CriticalSectionTest.Performance (1885 ms)
  345. //
  346. // The test is disabled by default to avoid unecessarily loading the bots.
  347. TEST(CriticalSectionTest, DISABLED_Performance) {
  348. PerfTestThread threads[8];
  349. Event event;
  350. static const int kThreadRepeats = 10000000;
  351. static const int kExpectedCount = kThreadRepeats * arraysize(threads);
  352. PerfTestData test_data(kExpectedCount, &event);
  353. for (auto& t : threads)
  354. t.Start(&test_data, kThreadRepeats, 1);
  355. event.Wait(Event::kForever);
  356. for (auto& t : threads)
  357. t.Stop();
  358. }
  359. } // namespace rtc