thread_manager.cc 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 <grpc/support/log.h>
  21. #include "src/core/lib/gprpp/thd.h"
  22. #include "src/core/lib/iomgr/exec_ctx.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, &created_);
  32. if (!created_) {
  33. gpr_log(GPR_ERROR, "Could not create grpc_sync_server worker-thread");
  34. }
  35. }
  36. void ThreadManager::WorkerThread::Run() {
  37. thd_mgr_->MainWorkLoop();
  38. thd_mgr_->MarkAsCompleted(this);
  39. }
  40. ThreadManager::WorkerThread::~WorkerThread() {
  41. // Don't join until the thread is fully constructed.
  42. thd_.Join();
  43. }
  44. ThreadManager::ThreadManager(const char*, grpc_resource_quota* resource_quota,
  45. int min_pollers, int max_pollers)
  46. : shutdown_(false),
  47. thread_quota_(
  48. grpc_core::ResourceQuota::FromC(resource_quota)->thread_quota()),
  49. num_pollers_(0),
  50. min_pollers_(min_pollers),
  51. max_pollers_(max_pollers == -1 ? INT_MAX : max_pollers),
  52. num_threads_(0),
  53. max_active_threads_sofar_(0) {}
  54. ThreadManager::~ThreadManager() {
  55. {
  56. grpc_core::MutexLock lock(&mu_);
  57. GPR_ASSERT(num_threads_ == 0);
  58. }
  59. CleanupCompletedThreads();
  60. }
  61. void ThreadManager::Wait() {
  62. grpc_core::MutexLock lock(&mu_);
  63. while (num_threads_ != 0) {
  64. shutdown_cv_.Wait(&mu_);
  65. }
  66. }
  67. void ThreadManager::Shutdown() {
  68. grpc_core::MutexLock lock(&mu_);
  69. shutdown_ = true;
  70. }
  71. bool ThreadManager::IsShutdown() {
  72. grpc_core::MutexLock lock(&mu_);
  73. return shutdown_;
  74. }
  75. int ThreadManager::GetMaxActiveThreadsSoFar() {
  76. grpc_core::MutexLock list_lock(&list_mu_);
  77. return max_active_threads_sofar_;
  78. }
  79. void ThreadManager::MarkAsCompleted(WorkerThread* thd) {
  80. {
  81. grpc_core::MutexLock list_lock(&list_mu_);
  82. completed_threads_.push_back(thd);
  83. }
  84. {
  85. grpc_core::MutexLock lock(&mu_);
  86. num_threads_--;
  87. if (num_threads_ == 0) {
  88. shutdown_cv_.Signal();
  89. }
  90. }
  91. // Give a thread back to the resource quota
  92. thread_quota_->Release(1);
  93. }
  94. void ThreadManager::CleanupCompletedThreads() {
  95. std::list<WorkerThread*> completed_threads;
  96. {
  97. // swap out the completed threads list: allows other threads to clean up
  98. // more quickly
  99. grpc_core::MutexLock lock(&list_mu_);
  100. completed_threads.swap(completed_threads_);
  101. }
  102. for (auto thd : completed_threads) delete thd;
  103. }
  104. void ThreadManager::Initialize() {
  105. if (!thread_quota_->Reserve(min_pollers_)) {
  106. gpr_log(GPR_ERROR,
  107. "No thread quota available to even create the minimum required "
  108. "polling threads (i.e %d). Unable to start the thread manager",
  109. min_pollers_);
  110. abort();
  111. }
  112. {
  113. grpc_core::MutexLock lock(&mu_);
  114. num_pollers_ = min_pollers_;
  115. num_threads_ = min_pollers_;
  116. max_active_threads_sofar_ = min_pollers_;
  117. }
  118. for (int i = 0; i < min_pollers_; i++) {
  119. WorkerThread* worker = new WorkerThread(this);
  120. GPR_ASSERT(worker->created()); // Must be able to create the minimum
  121. worker->Start();
  122. }
  123. }
  124. void ThreadManager::MainWorkLoop() {
  125. while (true) {
  126. void* tag;
  127. bool ok;
  128. WorkStatus work_status = PollForWork(&tag, &ok);
  129. grpc_core::LockableAndReleasableMutexLock lock(&mu_);
  130. // Reduce the number of pollers by 1 and check what happened with the poll
  131. num_pollers_--;
  132. bool done = false;
  133. switch (work_status) {
  134. case TIMEOUT:
  135. // If we timed out and we have more pollers than we need (or we are
  136. // shutdown), finish this thread
  137. if (shutdown_ || num_pollers_ > max_pollers_) done = true;
  138. break;
  139. case SHUTDOWN:
  140. // If the thread manager is shutdown, finish this thread
  141. done = true;
  142. break;
  143. case WORK_FOUND:
  144. // If we got work and there are now insufficient pollers and there is
  145. // quota available to create a new thread, start a new poller thread
  146. bool resource_exhausted = false;
  147. if (!shutdown_ && num_pollers_ < min_pollers_) {
  148. if (thread_quota_->Reserve(1)) {
  149. // We can allocate a new poller thread
  150. num_pollers_++;
  151. num_threads_++;
  152. if (num_threads_ > max_active_threads_sofar_) {
  153. max_active_threads_sofar_ = num_threads_;
  154. }
  155. // Drop lock before spawning thread to avoid contention
  156. lock.Release();
  157. WorkerThread* worker = new WorkerThread(this);
  158. if (worker->created()) {
  159. worker->Start();
  160. } else {
  161. // Get lock again to undo changes to poller/thread counters.
  162. grpc_core::MutexLock failure_lock(&mu_);
  163. num_pollers_--;
  164. num_threads_--;
  165. resource_exhausted = true;
  166. delete worker;
  167. }
  168. } else if (num_pollers_ > 0) {
  169. // There is still at least some thread polling, so we can go on
  170. // even though we are below the number of pollers that we would
  171. // like to have (min_pollers_)
  172. lock.Release();
  173. } else {
  174. // There are no pollers to spare and we couldn't allocate
  175. // a new thread, so resources are exhausted!
  176. lock.Release();
  177. resource_exhausted = true;
  178. }
  179. } else {
  180. // There are a sufficient number of pollers available so we can do
  181. // the work and continue polling with our existing poller threads
  182. lock.Release();
  183. }
  184. // Lock is always released at this point - do the application work
  185. // or return resource exhausted if there is new work but we couldn't
  186. // get a thread in which to do it.
  187. DoWork(tag, ok, !resource_exhausted);
  188. // Take the lock again to check post conditions
  189. lock.Lock();
  190. // If we're shutdown, we should finish at this point.
  191. if (shutdown_) done = true;
  192. break;
  193. }
  194. // If we decided to finish the thread, break out of the while loop
  195. if (done) break;
  196. // Otherwise go back to polling as long as it doesn't exceed max_pollers_
  197. //
  198. // **WARNING**:
  199. // There is a possibility of threads thrashing here (i.e excessive thread
  200. // shutdowns and creations than the ideal case). This happens if max_poller_
  201. // count is small and the rate of incoming requests is also small. In such
  202. // scenarios we can possibly configure max_pollers_ to a higher value and/or
  203. // increase the cq timeout.
  204. //
  205. // However, not doing this check here and unconditionally incrementing
  206. // num_pollers (and hoping that the system will eventually settle down) has
  207. // far worse consequences i.e huge number of threads getting created to the
  208. // point of thread-exhaustion. For example: if the incoming request rate is
  209. // very high, all the polling threads will return very quickly from
  210. // PollForWork() with WORK_FOUND. They all briefly decrement num_pollers_
  211. // counter thereby possibly - and briefly - making it go below min_pollers;
  212. // This will most likely result in the creation of a new poller since
  213. // num_pollers_ dipped below min_pollers_.
  214. //
  215. // Now, If we didn't do the max_poller_ check here, all these threads will
  216. // go back to doing PollForWork() and the whole cycle repeats (with a new
  217. // thread being added in each cycle). Once the total number of threads in
  218. // the system crosses a certain threshold (around ~1500), there is heavy
  219. // contention on mutexes (the mu_ here or the mutexes in gRPC core like the
  220. // pollset mutex) that makes DoWork() take longer to finish thereby causing
  221. // new poller threads to be created even faster. This results in a thread
  222. // avalanche.
  223. if (num_pollers_ < max_pollers_) {
  224. num_pollers_++;
  225. } else {
  226. break;
  227. }
  228. };
  229. // This thread is exiting. Do some cleanup work i.e delete already completed
  230. // worker threads
  231. CleanupCompletedThreads();
  232. // If we are here, either ThreadManager is shutting down or it already has
  233. // enough threads.
  234. }
  235. } // namespace grpc