per_thread_sem_test.cc 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/synchronization/internal/per_thread_sem.h"
  15. #include <atomic>
  16. #include <condition_variable> // NOLINT(build/c++11)
  17. #include <functional>
  18. #include <limits>
  19. #include <mutex> // NOLINT(build/c++11)
  20. #include <string>
  21. #include <thread> // NOLINT(build/c++11)
  22. #include "gtest/gtest.h"
  23. #include "absl/base/config.h"
  24. #include "absl/base/internal/cycleclock.h"
  25. #include "absl/base/internal/thread_identity.h"
  26. #include "absl/strings/str_cat.h"
  27. #include "absl/time/clock.h"
  28. #include "absl/time/time.h"
  29. // In this test we explicitly avoid the use of synchronization
  30. // primitives which might use PerThreadSem, most notably absl::Mutex.
  31. namespace absl {
  32. ABSL_NAMESPACE_BEGIN
  33. namespace synchronization_internal {
  34. class SimpleSemaphore {
  35. public:
  36. SimpleSemaphore() : count_(0) {}
  37. // Decrements (locks) the semaphore. If the semaphore's value is
  38. // greater than zero, then the decrement proceeds, and the function
  39. // returns, immediately. If the semaphore currently has the value
  40. // zero, then the call blocks until it becomes possible to perform
  41. // the decrement.
  42. void Wait() {
  43. std::unique_lock<std::mutex> lock(mu_);
  44. cv_.wait(lock, [this]() { return count_ > 0; });
  45. --count_;
  46. cv_.notify_one();
  47. }
  48. // Increments (unlocks) the semaphore. If the semaphore's value
  49. // consequently becomes greater than zero, then another thread
  50. // blocked Wait() call will be woken up and proceed to lock the
  51. // semaphore.
  52. void Post() {
  53. std::lock_guard<std::mutex> lock(mu_);
  54. ++count_;
  55. cv_.notify_one();
  56. }
  57. private:
  58. std::mutex mu_;
  59. std::condition_variable cv_;
  60. int count_;
  61. };
  62. struct ThreadData {
  63. int num_iterations; // Number of replies to send.
  64. SimpleSemaphore identity2_written; // Posted by thread writing identity2.
  65. base_internal::ThreadIdentity *identity1; // First Post()-er.
  66. base_internal::ThreadIdentity *identity2; // First Wait()-er.
  67. KernelTimeout timeout;
  68. };
  69. // Need friendship with PerThreadSem.
  70. class PerThreadSemTest : public testing::Test {
  71. public:
  72. static void TimingThread(ThreadData* t) {
  73. t->identity2 = GetOrCreateCurrentThreadIdentity();
  74. t->identity2_written.Post();
  75. while (t->num_iterations--) {
  76. Wait(t->timeout);
  77. Post(t->identity1);
  78. }
  79. }
  80. void TestTiming(const char *msg, bool timeout) {
  81. static const int kNumIterations = 100;
  82. ThreadData t;
  83. t.num_iterations = kNumIterations;
  84. t.timeout = timeout ?
  85. KernelTimeout(absl::Now() + absl::Seconds(10000)) // far in the future
  86. : KernelTimeout::Never();
  87. t.identity1 = GetOrCreateCurrentThreadIdentity();
  88. // We can't use the Thread class here because it uses the Mutex
  89. // class which will invoke PerThreadSem, so we use std::thread instead.
  90. std::thread partner_thread(std::bind(TimingThread, &t));
  91. // Wait for our partner thread to register their identity.
  92. t.identity2_written.Wait();
  93. int64_t min_cycles = std::numeric_limits<int64_t>::max();
  94. int64_t total_cycles = 0;
  95. for (int i = 0; i < kNumIterations; ++i) {
  96. absl::SleepFor(absl::Milliseconds(20));
  97. int64_t cycles = base_internal::CycleClock::Now();
  98. Post(t.identity2);
  99. Wait(t.timeout);
  100. cycles = base_internal::CycleClock::Now() - cycles;
  101. min_cycles = std::min(min_cycles, cycles);
  102. total_cycles += cycles;
  103. }
  104. std::string out = StrCat(
  105. msg, "min cycle count=", min_cycles, " avg cycle count=",
  106. absl::SixDigits(static_cast<double>(total_cycles) / kNumIterations));
  107. printf("%s\n", out.c_str());
  108. partner_thread.join();
  109. }
  110. protected:
  111. static void Post(base_internal::ThreadIdentity *id) {
  112. PerThreadSem::Post(id);
  113. }
  114. static bool Wait(KernelTimeout t) {
  115. return PerThreadSem::Wait(t);
  116. }
  117. // convenience overload
  118. static bool Wait(absl::Time t) {
  119. return Wait(KernelTimeout(t));
  120. }
  121. static void Tick(base_internal::ThreadIdentity *identity) {
  122. PerThreadSem::Tick(identity);
  123. }
  124. };
  125. namespace {
  126. TEST_F(PerThreadSemTest, WithoutTimeout) {
  127. PerThreadSemTest::TestTiming("Without timeout: ", false);
  128. }
  129. TEST_F(PerThreadSemTest, WithTimeout) {
  130. PerThreadSemTest::TestTiming("With timeout: ", true);
  131. }
  132. TEST_F(PerThreadSemTest, Timeouts) {
  133. const absl::Duration delay = absl::Milliseconds(50);
  134. const absl::Time start = absl::Now();
  135. EXPECT_FALSE(Wait(start + delay));
  136. const absl::Duration elapsed = absl::Now() - start;
  137. // Allow for a slight early return, to account for quality of implementation
  138. // issues on various platforms.
  139. const absl::Duration slop = absl::Milliseconds(1);
  140. EXPECT_LE(delay - slop, elapsed)
  141. << "Wait returned " << delay - elapsed
  142. << " early (with " << slop << " slop), start time was " << start;
  143. absl::Time negative_timeout = absl::UnixEpoch() - absl::Milliseconds(100);
  144. EXPECT_FALSE(Wait(negative_timeout));
  145. EXPECT_LE(negative_timeout, absl::Now() + slop); // trivially true :)
  146. Post(GetOrCreateCurrentThreadIdentity());
  147. // The wait here has an expired timeout, but we have a wake to consume,
  148. // so this should succeed
  149. EXPECT_TRUE(Wait(negative_timeout));
  150. }
  151. } // namespace
  152. } // namespace synchronization_internal
  153. ABSL_NAMESPACE_END
  154. } // namespace absl