Debian Codegraph @

src/core/lib/event_engine/thread_pool.cc

raw
1 /*
2 *
3 * Copyright 2015 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
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/event_engine/thread_pool.h"
22
23 #include <atomic>
24 #include <memory>
25 #include <utility>
26
27 #include "absl/base/attributes.h"
28 #include "absl/time/clock.h"
29 #include "absl/time/time.h"
30
31 #include <grpc/support/log.h>
32
33 #include "src/core/lib/gprpp/thd.h"
34 #include "src/core/lib/gprpp/time.h"
35
36 namespace grpc_event_engine {
37 namespace experimental {
38
39 namespace {
40 // TODO(drfloob): Remove this, and replace it with the WorkQueue* for the
41 // current thread (with nullptr indicating not a threadpool thread).
42 thread_local bool g_threadpool_thread;
43 } // namespace
44
45 void ThreadPool::StartThread(StatePtr state, StartThreadReason reason) {
46 state->thread_count.Add();
47 const auto now = grpc_core::Timestamp::Now();
48 switch (reason) {
49 case StartThreadReason::kNoWaitersWhenScheduling: {
50 auto time_since_last_start =
51 now - grpc_core::Timestamp::FromMillisecondsAfterProcessEpoch(
52 state->last_started_thread.load(std::memory_order_relaxed));
53 if (time_since_last_start < grpc_core::Duration::Seconds(1)) {
54 state->thread_count.Remove();
55 return;
56 }
57 }
58 ABSL_FALLTHROUGH_INTENDED;
59 case StartThreadReason::kNoWaitersWhenFinishedStarting:
60 if (state->currently_starting_one_thread.exchange(
61 true, std::memory_order_relaxed)) {
62 state->thread_count.Remove();
63 return;
64 }
65 state->last_started_thread.store(now.milliseconds_after_process_epoch(),
66 std::memory_order_relaxed);
67 break;
68 case StartThreadReason::kInitialPool:
69 break;
70 }
71 struct ThreadArg {
72 StatePtr state;
73 StartThreadReason reason;
74 };
75 grpc_core::Thread(
76 "event_engine",
77 [](void* arg) {
78 std::unique_ptr<ThreadArg> a(static_cast<ThreadArg*>(arg));
79 g_threadpool_thread = true;
80 switch (a->reason) {
81 case StartThreadReason::kInitialPool:
82 break;
83 case StartThreadReason::kNoWaitersWhenFinishedStarting:
84 a->state->queue.SleepIfRunning();
85 ABSL_FALLTHROUGH_INTENDED;
86 case StartThreadReason::kNoWaitersWhenScheduling:
87 // Release throttling variable
88 GPR_ASSERT(a->state->currently_starting_one_thread.exchange(
89 false, std::memory_order_relaxed));
90 if (a->state->queue.IsBacklogged()) {
91 StartThread(a->state,
92 StartThreadReason::kNoWaitersWhenFinishedStarting);
93 }
94 break;
95 }
96 ThreadFunc(a->state);
97 },
98 new ThreadArg{state, reason}, nullptr,
99 grpc_core::Thread::Options().set_tracked(false).set_joinable(false))
100 .Start();
101 }
102
103 void ThreadPool::ThreadFunc(StatePtr state) {
104 while (state->queue.Step()) {
105 }
106 state->thread_count.Remove();
107 }
108
109 bool ThreadPool::Queue::Step() {
110 grpc_core::ReleasableMutexLock lock(&mu_);
111 // Wait until work is available or we are shutting down.
112 while (state_ == State::kRunning && callbacks_.empty()) {
113 // If there are too many threads waiting, then quit this thread.
114 // TODO(ctiller): wait some time in this case to be sure.
115 if (threads_waiting_ >= reserve_threads_) {
116 threads_waiting_++;
117 bool timeout = cv_.WaitWithTimeout(&mu_, absl::Seconds(30));
118 threads_waiting_--;
119 if (timeout && threads_waiting_ >= reserve_threads_) {
120 return false;
121 }
122 } else {
123 threads_waiting_++;
124 cv_.Wait(&mu_);
125 threads_waiting_--;
126 }
127 }
128 switch (state_) {
129 case State::kRunning:
130 break;
131 case State::kShutdown:
132 case State::kForking:
133 if (!callbacks_.empty()) break;
134 return false;
135 }
136 GPR_ASSERT(!callbacks_.empty());
137 auto callback = std::move(callbacks_.front());
138 callbacks_.pop();
139 lock.Release();
140 callback();
141 return true;
142 }
143
144 ThreadPool::ThreadPool() {
145 for (unsigned i = 0; i < reserve_threads_; i++) {
146 StartThread(state_, StartThreadReason::kInitialPool);
147 }
148 }
149
150 void ThreadPool::Quiesce() {
151 state_->queue.SetShutdown();
152 // Wait until all threads are exited.
153 // Note that if this is a threadpool thread then we won't exit this thread
154 // until the callstack unwinds a little, so we need to wait for just one
155 // thread running instead of zero.
156 state_->thread_count.BlockUntilThreadCount(g_threadpool_thread ? 1 : 0,
157 "shutting down");
158 quiesced_.store(true, std::memory_order_relaxed);
159 }
160
161 ThreadPool::~ThreadPool() {
162 GPR_ASSERT(quiesced_.load(std::memory_order_relaxed));
163 }
164
165 void ThreadPool::Run(absl::AnyInvocable<void()> callback) {
166 GPR_DEBUG_ASSERT(quiesced_.load(std::memory_order_relaxed) == false);
167 if (state_->queue.Add(std::move(callback))) {
168 StartThread(state_, StartThreadReason::kNoWaitersWhenScheduling);
169 }
170 }
171
172 void ThreadPool::Run(EventEngine::Closure* closure) {
173 Run([closure]() { closure->Run(); });
174 }
175
176 bool ThreadPool::Queue::Add(absl::AnyInvocable<void()> callback) {
177 grpc_core::MutexLock lock(&mu_);
178 // Add works to the callbacks list
179 callbacks_.push(std::move(callback));
180 cv_.Signal();
181 switch (state_) {
182 case State::kRunning:
183 case State::kShutdown:
184 return callbacks_.size() > threads_waiting_;
185 case State::kForking:
186 return false;
187 }
188 GPR_UNREACHABLE_CODE(return false);
189 }
190
191 bool ThreadPool::Queue::IsBacklogged() {
192 grpc_core::MutexLock lock(&mu_);
193 switch (state_) {
194 case State::kRunning:
195 case State::kShutdown:
196 return callbacks_.size() > 1;
197 case State::kForking:
198 return false;
199 }
200 GPR_UNREACHABLE_CODE(return false);
201 }
202
203 void ThreadPool::Queue::SleepIfRunning() {
204 grpc_core::MutexLock lock(&mu_);
205 auto end = grpc_core::Duration::Seconds(1) + grpc_core::Timestamp::Now();
206 while (true) {
207 grpc_core::Timestamp now = grpc_core::Timestamp::Now();
208 if (now >= end) return;
209 switch (state_) {
210 case State::kRunning:
211 case State::kShutdown:
212 cv_.WaitWithTimeout(&mu_, absl::Milliseconds((end - now).millis()));
213 break;
214 case State::kForking:
215 return;
216 }
217 }
218 }
219
220 void ThreadPool::Queue::SetState(State state) {
221 grpc_core::MutexLock lock(&mu_);
222 if (state == State::kRunning) {
223 GPR_ASSERT(state_ != State::kRunning);
224 } else {
225 GPR_ASSERT(state_ == State::kRunning);
226 }
227 state_ = state;
228 cv_.SignalAll();
229 }
230
231 void ThreadPool::ThreadCount::Add() {
232 grpc_core::MutexLock lock(&mu_);
233 ++threads_;
234 }
235
236 void ThreadPool::ThreadCount::Remove() {
237 grpc_core::MutexLock lock(&mu_);
238 --threads_;
239 cv_.Signal();
240 }
241
242 void ThreadPool::ThreadCount::BlockUntilThreadCount(int threads,
243 const char* why) {
244 grpc_core::MutexLock lock(&mu_);
245 auto last_log = absl::Now();
246 while (threads_ > threads) {
247 // Wait for all threads to exit.
248 // At least once every three seconds (but no faster than once per second in
249 // the event of spurious wakeups) log a message indicating we're waiting to
250 // fork.
251 cv_.WaitWithTimeout(&mu_, absl::Seconds(3));
252 if (threads_ > threads && absl::Now() - last_log > absl::Seconds(1)) {
253 gpr_log(GPR_ERROR, "Waiting for thread pool to idle before %s", why);
254 last_log = absl::Now();
255 }
256 }
257 }
258
259 void ThreadPool::PrepareFork() {
260 state_->queue.SetForking();
261 state_->thread_count.BlockUntilThreadCount(0, "forking");
262 }
263
264 void ThreadPool::PostforkParent() { Postfork(); }
265
266 void ThreadPool::PostforkChild() { Postfork(); }
267
268 void ThreadPool::Postfork() {
269 state_->queue.Reset();
270 for (unsigned i = 0; i < reserve_threads_; i++) {
271 StartThread(state_, StartThreadReason::kInitialPool);
272 }
273 }
274
275 } // namespace experimental
276 } // namespace grpc_event_engine