thread_manager.cc 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /*
  2. *
  3. * Copyright 2016 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include "src/cpp/thread_manager/thread_manager.h"
  19. #include <climits>
  20. #include <mutex>
  21. #include <grpc/support/log.h>
  22. #include "src/core/lib/gprpp/thd.h"
  23. namespace grpc {
  24. ThreadManager::WorkerThread::WorkerThread(ThreadManager* thd_mgr)
  25. : thd_mgr_(thd_mgr) {
  26. // Make thread creation exclusive with respect to its join happening in
  27. // ~WorkerThread().
  28. thd_ = grpc_core::Thread(
  29. "grpcpp_sync_server",
  30. [](void* th) { static_cast<ThreadManager::WorkerThread*>(th)->Run(); },
  31. this);
  32. thd_.Start();
  33. }
  34. void ThreadManager::WorkerThread::Run() {
  35. thd_mgr_->MainWorkLoop();
  36. thd_mgr_->MarkAsCompleted(this);
  37. }
  38. ThreadManager::WorkerThread::~WorkerThread() {
  39. // Don't join until the thread is fully constructed.
  40. thd_.Join();
  41. }
  42. ThreadManager::ThreadManager(int min_pollers, int max_pollers)
  43. : shutdown_(false),
  44. num_pollers_(0),
  45. min_pollers_(min_pollers),
  46. max_pollers_(max_pollers == -1 ? INT_MAX : max_pollers),
  47. num_threads_(0) {}
  48. ThreadManager::~ThreadManager() {
  49. {
  50. std::lock_guard<std::mutex> lock(mu_);
  51. GPR_ASSERT(num_threads_ == 0);
  52. }
  53. CleanupCompletedThreads();
  54. }
  55. void ThreadManager::Wait() {
  56. std::unique_lock<std::mutex> lock(mu_);
  57. while (num_threads_ != 0) {
  58. shutdown_cv_.wait(lock);
  59. }
  60. }
  61. void ThreadManager::Shutdown() {
  62. std::lock_guard<std::mutex> lock(mu_);
  63. shutdown_ = true;
  64. }
  65. bool ThreadManager::IsShutdown() {
  66. std::lock_guard<std::mutex> lock(mu_);
  67. return shutdown_;
  68. }
  69. void ThreadManager::MarkAsCompleted(WorkerThread* thd) {
  70. {
  71. std::lock_guard<std::mutex> list_lock(list_mu_);
  72. completed_threads_.push_back(thd);
  73. }
  74. std::lock_guard<std::mutex> lock(mu_);
  75. num_threads_--;
  76. if (num_threads_ == 0) {
  77. shutdown_cv_.notify_one();
  78. }
  79. }
  80. void ThreadManager::CleanupCompletedThreads() {
  81. std::list<WorkerThread*> completed_threads;
  82. {
  83. // swap out the completed threads list: allows other threads to clean up
  84. // more quickly
  85. std::unique_lock<std::mutex> lock(list_mu_);
  86. completed_threads.swap(completed_threads_);
  87. }
  88. for (auto thd : completed_threads) delete thd;
  89. }
  90. void ThreadManager::Initialize() {
  91. {
  92. std::unique_lock<std::mutex> lock(mu_);
  93. num_pollers_ = min_pollers_;
  94. num_threads_ = min_pollers_;
  95. }
  96. for (int i = 0; i < min_pollers_; i++) {
  97. // Create a new thread (which ends up calling the MainWorkLoop() function
  98. new WorkerThread(this);
  99. }
  100. }
  101. void ThreadManager::MainWorkLoop() {
  102. while (true) {
  103. void* tag;
  104. bool ok;
  105. WorkStatus work_status = PollForWork(&tag, &ok);
  106. std::unique_lock<std::mutex> lock(mu_);
  107. // Reduce the number of pollers by 1 and check what happened with the poll
  108. num_pollers_--;
  109. bool done = false;
  110. switch (work_status) {
  111. case TIMEOUT:
  112. // If we timed out and we have more pollers than we need (or we are
  113. // shutdown), finish this thread
  114. if (shutdown_ || num_pollers_ > max_pollers_) done = true;
  115. break;
  116. case SHUTDOWN:
  117. // If the thread manager is shutdown, finish this thread
  118. done = true;
  119. break;
  120. case WORK_FOUND:
  121. // If we got work and there are now insufficient pollers, start a new
  122. // one
  123. if (!shutdown_ && num_pollers_ < min_pollers_) {
  124. num_pollers_++;
  125. num_threads_++;
  126. // Drop lock before spawning thread to avoid contention
  127. lock.unlock();
  128. new WorkerThread(this);
  129. } else {
  130. // Drop lock for consistency with above branch
  131. lock.unlock();
  132. }
  133. // Lock is always released at this point - do the application work
  134. DoWork(tag, ok);
  135. // Take the lock again to check post conditions
  136. lock.lock();
  137. // If we're shutdown, we should finish at this point.
  138. if (shutdown_) done = true;
  139. break;
  140. }
  141. // If we decided to finish the thread, break out of the while loop
  142. if (done) break;
  143. // Otherwise go back to polling as long as it doesn't exceed max_pollers_
  144. //
  145. // **WARNING**:
  146. // There is a possibility of threads thrashing here (i.e excessive thread
  147. // shutdowns and creations than the ideal case). This happens if max_poller_
  148. // count is small and the rate of incoming requests is also small. In such
  149. // scenarios we can possibly configure max_pollers_ to a higher value and/or
  150. // increase the cq timeout.
  151. //
  152. // However, not doing this check here and unconditionally incrementing
  153. // num_pollers (and hoping that the system will eventually settle down) has
  154. // far worse consequences i.e huge number of threads getting created to the
  155. // point of thread-exhaustion. For example: if the incoming request rate is
  156. // very high, all the polling threads will return very quickly from
  157. // PollForWork() with WORK_FOUND. They all briefly decrement num_pollers_
  158. // counter thereby possibly - and briefly - making it go below min_pollers;
  159. // This will most likely result in the creation of a new poller since
  160. // num_pollers_ dipped below min_pollers_.
  161. //
  162. // Now, If we didn't do the max_poller_ check here, all these threads will
  163. // go back to doing PollForWork() and the whole cycle repeats (with a new
  164. // thread being added in each cycle). Once the total number of threads in
  165. // the system crosses a certain threshold (around ~1500), there is heavy
  166. // contention on mutexes (the mu_ here or the mutexes in gRPC core like the
  167. // pollset mutex) that makes DoWork() take longer to finish thereby causing
  168. // new poller threads to be created even faster. This results in a thread
  169. // avalanche.
  170. if (num_pollers_ < max_pollers_) {
  171. num_pollers_++;
  172. } else {
  173. break;
  174. }
  175. };
  176. CleanupCompletedThreads();
  177. // If we are here, either ThreadManager is shutting down or it already has
  178. // enough threads.
  179. }
  180. } // namespace grpc