thread_manager.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. #ifndef GRPC_INTERNAL_CPP_THREAD_MANAGER_H
  19. #define GRPC_INTERNAL_CPP_THREAD_MANAGER_H
  20. #include <list>
  21. #include <memory>
  22. #include <grpc/grpc.h>
  23. #include <grpcpp/support/config.h>
  24. #include "src/core/lib/gprpp/sync.h"
  25. #include "src/core/lib/gprpp/thd.h"
  26. #include "src/core/lib/resource_quota/api.h"
  27. namespace grpc {
  28. class ThreadManager {
  29. public:
  30. explicit ThreadManager(const char* name, grpc_resource_quota* resource_quota,
  31. int min_pollers, int max_pollers);
  32. virtual ~ThreadManager();
  33. // Initializes and Starts the Rpc Manager threads
  34. void Initialize();
  35. // The return type of PollForWork() function
  36. enum WorkStatus { WORK_FOUND, SHUTDOWN, TIMEOUT };
  37. // "Polls" for new work.
  38. // If the return value is WORK_FOUND:
  39. // - The implementaion of PollForWork() MAY set some opaque identifier to
  40. // (identify the work item found) via the '*tag' parameter
  41. // - The implementaion MUST set the value of 'ok' to 'true' or 'false'. A
  42. // value of 'false' indicates some implemenation specific error (that is
  43. // neither SHUTDOWN nor TIMEOUT)
  44. // - ThreadManager does not interpret the values of 'tag' and 'ok'
  45. // - ThreadManager WILL call DoWork() and pass '*tag' and 'ok' as input to
  46. // DoWork()
  47. //
  48. // If the return value is SHUTDOWN:,
  49. // - ThreadManager WILL NOT call DoWork() and terminates the thread
  50. //
  51. // If the return value is TIMEOUT:,
  52. // - ThreadManager WILL NOT call DoWork()
  53. // - ThreadManager MAY terminate the thread depending on the current number
  54. // of active poller threads and mix_pollers/max_pollers settings
  55. // - Also, the value of timeout is specific to the derived class
  56. // implementation
  57. virtual WorkStatus PollForWork(void** tag, bool* ok) = 0;
  58. // The implementation of DoWork() is supposed to perform the work found by
  59. // PollForWork(). The tag and ok parameters are the same as returned by
  60. // PollForWork(). The resources parameter indicates that the call actually
  61. // has the resources available for performing the RPC's work. If it doesn't,
  62. // the implementation should fail it appropriately.
  63. //
  64. // The implementation of DoWork() should also do any setup needed to ensure
  65. // that the next call to PollForWork() (not necessarily by the current thread)
  66. // actually finds some work
  67. virtual void DoWork(void* tag, bool ok, bool resources) = 0;
  68. // Mark the ThreadManager as shutdown and begin draining the work. This is a
  69. // non-blocking call and the caller should call Wait(), a blocking call which
  70. // returns only once the shutdown is complete
  71. virtual void Shutdown();
  72. // Has Shutdown() been called
  73. bool IsShutdown();
  74. // A blocking call that returns only after the ThreadManager has shutdown and
  75. // all the threads have drained all the outstanding work
  76. virtual void Wait();
  77. // Max number of concurrent threads that were ever active in this thread
  78. // manager so far. This is useful for debugging purposes (and in unit tests)
  79. // to check if resource_quota is properly being enforced.
  80. int GetMaxActiveThreadsSoFar();
  81. private:
  82. // Helper wrapper class around grpc_core::Thread. Takes a ThreadManager object
  83. // and starts a new grpc_core::Thread to calls the Run() function.
  84. //
  85. // The Run() function calls ThreadManager::MainWorkLoop() function and once
  86. // that completes, it marks the WorkerThread completed by calling
  87. // ThreadManager::MarkAsCompleted()
  88. //
  89. // WHY IS THIS NEEDED?:
  90. // When a thread terminates, some other thread *must* call Join() on that
  91. // thread so that the resources are released. Having a WorkerThread wrapper
  92. // will make this easier. Once Run() completes, each thread calls the
  93. // following two functions:
  94. // ThreadManager::CleanupCompletedThreads()
  95. // ThreadManager::MarkAsCompleted()
  96. //
  97. // - MarkAsCompleted() puts the WorkerThread object in the ThreadManger's
  98. // completed_threads_ list
  99. // - CleanupCompletedThreads() calls "Join()" on the threads that are already
  100. // in the completed_threads_ list (since a thread cannot call Join() on
  101. // itself, it calls CleanupCompletedThreads() *before* calling
  102. // MarkAsCompleted())
  103. //
  104. // TODO(sreek): Consider creating the threads 'detached' so that Join() need
  105. // not be called (and the need for this WorkerThread class is eliminated)
  106. class WorkerThread {
  107. public:
  108. explicit WorkerThread(ThreadManager* thd_mgr);
  109. ~WorkerThread();
  110. bool created() const { return created_; }
  111. void Start() { thd_.Start(); }
  112. private:
  113. // Calls thd_mgr_->MainWorkLoop() and once that completes, calls
  114. // thd_mgr_>MarkAsCompleted(this) to mark the thread as completed
  115. void Run();
  116. ThreadManager* const thd_mgr_;
  117. grpc_core::Thread thd_;
  118. bool created_;
  119. };
  120. // The main function in ThreadManager
  121. void MainWorkLoop();
  122. void MarkAsCompleted(WorkerThread* thd);
  123. void CleanupCompletedThreads();
  124. // Protects shutdown_, num_pollers_, num_threads_ and
  125. // max_active_threads_sofar_
  126. grpc_core::Mutex mu_;
  127. bool shutdown_;
  128. grpc_core::CondVar shutdown_cv_;
  129. // The resource user object to use when requesting quota to create threads
  130. //
  131. // Note: The user of this ThreadManager object must create grpc_resource_quota
  132. // object (that contains the actual max thread quota) and a grpc_resource_user
  133. // object through which quota is requested whenever new threads need to be
  134. // created
  135. grpc_core::ThreadQuotaPtr thread_quota_;
  136. // Number of threads doing polling
  137. int num_pollers_;
  138. // The minimum and maximum number of threads that should be doing polling
  139. int min_pollers_;
  140. int max_pollers_;
  141. // The total number of threads currently active (includes threads includes the
  142. // threads that are currently polling i.e num_pollers_)
  143. int num_threads_;
  144. // See GetMaxActiveThreadsSoFar()'s description.
  145. // To be more specific, this variable tracks the max value num_threads_ was
  146. // ever set so far
  147. int max_active_threads_sofar_;
  148. grpc_core::Mutex list_mu_;
  149. std::list<WorkerThread*> completed_threads_;
  150. };
  151. } // namespace grpc
  152. #endif // GRPC_INTERNAL_CPP_THREAD_MANAGER_H