thread_manager.cc 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. *
  3. * Copyright 2016, Google Inc.
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are
  8. * met:
  9. *
  10. * * Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * * Redistributions in binary form must reproduce the above
  13. * copyright notice, this list of conditions and the following disclaimer
  14. * in the documentation and/or other materials provided with the
  15. * distribution.
  16. * * Neither the name of Google Inc. nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #include <grpc++/impl/sync.h>
  34. #include <grpc++/impl/thd.h>
  35. #include <grpc/support/log.h>
  36. #include <climits>
  37. #include "src/cpp/thread_manager/thread_manager.h"
  38. namespace grpc {
  39. ThreadManager::WorkerThread::WorkerThread(ThreadManager* thd_mgr)
  40. : thd_mgr_(thd_mgr), thd_(&ThreadManager::WorkerThread::Run, this) {}
  41. void ThreadManager::WorkerThread::Run() {
  42. thd_mgr_->MainWorkLoop();
  43. thd_mgr_->MarkAsCompleted(this);
  44. }
  45. ThreadManager::WorkerThread::~WorkerThread() { thd_.join(); }
  46. ThreadManager::ThreadManager(int min_pollers, int max_pollers)
  47. : shutdown_(false),
  48. num_pollers_(0),
  49. min_pollers_(min_pollers),
  50. max_pollers_(max_pollers == -1 ? INT_MAX : max_pollers),
  51. num_threads_(0) {}
  52. ThreadManager::~ThreadManager() {
  53. {
  54. std::unique_lock<grpc::mutex> lock(mu_);
  55. GPR_ASSERT(num_threads_ == 0);
  56. }
  57. CleanupCompletedThreads();
  58. }
  59. void ThreadManager::Wait() {
  60. std::unique_lock<grpc::mutex> lock(mu_);
  61. while (num_threads_ != 0) {
  62. shutdown_cv_.wait(lock);
  63. }
  64. }
  65. void ThreadManager::Shutdown() {
  66. std::unique_lock<grpc::mutex> lock(mu_);
  67. shutdown_ = true;
  68. }
  69. bool ThreadManager::IsShutdown() {
  70. std::unique_lock<grpc::mutex> lock(mu_);
  71. return shutdown_;
  72. }
  73. void ThreadManager::MarkAsCompleted(WorkerThread* thd) {
  74. {
  75. std::unique_lock<grpc::mutex> list_lock(list_mu_);
  76. completed_threads_.push_back(thd);
  77. }
  78. grpc::unique_lock<grpc::mutex> lock(mu_);
  79. num_threads_--;
  80. if (num_threads_ == 0) {
  81. shutdown_cv_.notify_one();
  82. }
  83. }
  84. void ThreadManager::CleanupCompletedThreads() {
  85. std::unique_lock<grpc::mutex> lock(list_mu_);
  86. for (auto thd = completed_threads_.begin(); thd != completed_threads_.end();
  87. thd = completed_threads_.erase(thd)) {
  88. delete *thd;
  89. }
  90. }
  91. void ThreadManager::Initialize() {
  92. for (int i = 0; i < min_pollers_; i++) {
  93. MaybeCreatePoller();
  94. }
  95. }
  96. // If the number of pollers (i.e threads currently blocked in PollForWork()) is
  97. // less than max threshold (i.e max_pollers_) and the total number of threads is
  98. // below the maximum threshold, we can let the current thread continue as poller
  99. bool ThreadManager::MaybeContinueAsPoller() {
  100. std::unique_lock<grpc::mutex> lock(mu_);
  101. if (shutdown_ || num_pollers_ > max_pollers_) {
  102. return false;
  103. }
  104. num_pollers_++;
  105. return true;
  106. }
  107. // Create a new poller if the current number of pollers i.e num_pollers_ (i.e
  108. // threads currently blocked in PollForWork()) is below the threshold (i.e
  109. // min_pollers_) and the total number of threads is below the maximum threshold
  110. void ThreadManager::MaybeCreatePoller() {
  111. grpc::unique_lock<grpc::mutex> lock(mu_);
  112. if (!shutdown_ && num_pollers_ < min_pollers_) {
  113. num_pollers_++;
  114. num_threads_++;
  115. // Create a new thread (which ends up calling the MainWorkLoop() function
  116. new WorkerThread(this);
  117. }
  118. }
  119. void ThreadManager::MainWorkLoop() {
  120. void* tag;
  121. bool ok;
  122. /*
  123. 1. Poll for work (i.e PollForWork())
  124. 2. After returning from PollForWork, reduce the number of pollers by 1. If
  125. PollForWork() returned a TIMEOUT, then it may indicate that we have more
  126. polling threads than needed. Check if the number of pollers is greater
  127. than min_pollers and if so, terminate the thread.
  128. 3. Since we are short of one poller now, see if a new poller has to be
  129. created (i.e see MaybeCreatePoller() for more details)
  130. 4. Do the actual work (DoWork())
  131. 5. After doing the work, see it this thread can resume polling work (i.e
  132. see MaybeContinueAsPoller() for more details) */
  133. do {
  134. WorkStatus work_status = PollForWork(&tag, &ok);
  135. {
  136. grpc::unique_lock<grpc::mutex> lock(mu_);
  137. num_pollers_--;
  138. if (work_status == TIMEOUT && num_pollers_ > min_pollers_) {
  139. break;
  140. }
  141. }
  142. // Note that MaybeCreatePoller does check for shutdown and creates a new
  143. // thread only if ThreadManager is not shutdown
  144. if (work_status == WORK_FOUND) {
  145. MaybeCreatePoller();
  146. DoWork(tag, ok);
  147. }
  148. } while (MaybeContinueAsPoller());
  149. CleanupCompletedThreads();
  150. // If we are here, either ThreadManager is shutting down or it already has
  151. // enough threads.
  152. }
  153. } // namespace grpc