| 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/iomgr/executor.h" |
| 22 |
|
| 23 |
#include <string.h> |
| 24 |
|
| 25 |
#include <grpc/support/alloc.h> |
| 26 |
#include <grpc/support/cpu.h> |
| 27 |
#include <grpc/support/log.h> |
| 28 |
#include <grpc/support/sync.h> |
| 29 |
|
| 30 |
#include "src/core/lib/gpr/useful.h" |
| 31 |
#include "src/core/lib/gprpp/memory.h" |
| 32 |
#include "src/core/lib/iomgr/exec_ctx.h" |
| 33 |
#include "src/core/lib/iomgr/iomgr_internal.h" |
| 34 |
|
| 35 |
#define MAX_DEPTH 2 |
| 36 |
|
| 37 |
#define EXECUTOR_TRACE(format, ...) \ |
| 38 |
do { \ |
| 39 |
if (GRPC_TRACE_FLAG_ENABLED(executor_trace)) { \ |
| 40 |
gpr_log(GPR_INFO, "EXECUTOR " format, __VA_ARGS__); \ |
| 41 |
} \ |
| 42 |
} while (0) |
| 43 |
|
| 44 |
#define EXECUTOR_TRACE0(str) \ |
| 45 |
do { \ |
| 46 |
if (GRPC_TRACE_FLAG_ENABLED(executor_trace)) { \ |
| 47 |
gpr_log(GPR_INFO, "EXECUTOR " str); \ |
| 48 |
} \ |
| 49 |
} while (0) |
| 50 |
|
| 51 |
namespace grpc_core { |
| 52 |
namespace { |
| 53 |
|
| 54 |
thread_local ThreadState* g_this_thread_state; |
| 55 |
|
| 56 |
Executor* executors[static_cast<size_t>(ExecutorType::NUM_EXECUTORS)]; |
| 57 |
|
| 58 |
void default_enqueue_short(grpc_closure* closure, grpc_error_handle error) { |
| 59 |
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Enqueue( |
| 60 |
closure, error, true /* is_short */); |
| 61 |
} |
| 62 |
|
| 63 |
void default_enqueue_long(grpc_closure* closure, grpc_error_handle error) { |
| 64 |
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Enqueue( |
| 65 |
closure, error, false /* is_short */); |
| 66 |
} |
| 67 |
|
| 68 |
void resolver_enqueue_short(grpc_closure* closure, grpc_error_handle error) { |
| 69 |
executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Enqueue( |
| 70 |
closure, error, true /* is_short */); |
| 71 |
} |
| 72 |
|
| 73 |
void resolver_enqueue_long(grpc_closure* closure, grpc_error_handle error) { |
| 74 |
executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Enqueue( |
| 75 |
closure, error, false /* is_short */); |
| 76 |
} |
| 77 |
|
| 78 |
using EnqueueFunc = void (*)(grpc_closure* closure, grpc_error_handle error); |
| 79 |
|
| 80 |
const EnqueueFunc |
| 81 |
executor_enqueue_fns_[static_cast<size_t>(ExecutorType::NUM_EXECUTORS)] |
| 82 |
[static_cast<size_t>(ExecutorJobType::NUM_JOB_TYPES)] = |
| 83 |
{{default_enqueue_short, default_enqueue_long}, |
| 84 |
{resolver_enqueue_short, resolver_enqueue_long}}; |
| 85 |
|
| 86 |
} // namespace |
| 87 |
|
| 88 |
TraceFlag executor_trace(false, "executor"); |
| 89 |
|
| 90 |
Executor::Executor(const char* name) : name_(name) { |
| 91 |
adding_thread_lock_ = GPR_SPINLOCK_STATIC_INITIALIZER; |
| 92 |
gpr_atm_rel_store(&num_threads_, 0); |
| 93 |
max_threads_ = std::max(1u, 2 * gpr_cpu_num_cores()); |
| 94 |
} |
| 95 |
|
| 96 |
void Executor::Init() { SetThreading(true); } |
| 97 |
|
| 98 |
size_t Executor::RunClosures(const char* executor_name, |
| 99 |
grpc_closure_list list) { |
| 100 |
size_t n = 0; |
| 101 |
|
| 102 |
// In the executor, the ExecCtx for the thread is declared in the executor |
| 103 |
// thread itself, but this is the point where we could start seeing |
| 104 |
// application-level callbacks. No need to create a new ExecCtx, though, |
| 105 |
// since there already is one and it is flushed (but not destructed) in this |
| 106 |
// function itself. The ApplicationCallbackExecCtx will have its callbacks |
| 107 |
// invoked on its destruction, which will be after completing any closures in |
| 108 |
// the executor's closure list (which were explicitly scheduled onto the |
| 109 |
// executor). |
| 110 |
ApplicationCallbackExecCtx callback_exec_ctx( |
| 111 |
GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); |
| 112 |
|
| 113 |
grpc_closure* c = list.head; |
| 114 |
while (c != nullptr) { |
| 115 |
grpc_closure* next = c->next_data.next; |
| 116 |
#ifndef NDEBUG |
| 117 |
EXECUTOR_TRACE("(%s) run %p [created by %s:%d]", executor_name, c, |
| 118 |
c->file_created, c->line_created); |
| 119 |
c->scheduled = false; |
| 120 |
#else |
| 121 |
EXECUTOR_TRACE("(%s) run %p", executor_name, c); |
| 122 |
#endif |
| 123 |
grpc_error_handle error = |
| 124 |
internal::StatusMoveFromHeapPtr(c->error_data.error); |
| 125 |
c->error_data.error = 0; |
| 126 |
c->cb(c->cb_arg, std::move(error)); |
| 127 |
c = next; |
| 128 |
n++; |
| 129 |
ExecCtx::Get()->Flush(); |
| 130 |
} |
| 131 |
|
| 132 |
return n; |
| 133 |
} |
| 134 |
|
| 135 |
bool Executor::IsThreaded() const { |
| 136 |
return gpr_atm_acq_load(&num_threads_) > 0; |
| 137 |
} |
| 138 |
|
| 139 |
void Executor::SetThreading(bool threading) { |
| 140 |
gpr_atm curr_num_threads = gpr_atm_acq_load(&num_threads_); |
| 141 |
EXECUTOR_TRACE("(%s) SetThreading(%d) begin", name_, threading); |
| 142 |
|
| 143 |
if (threading) { |
| 144 |
if (curr_num_threads > 0) { |
| 145 |
EXECUTOR_TRACE("(%s) SetThreading(true). curr_num_threads > 0", name_); |
| 146 |
return; |
| 147 |
} |
| 148 |
|
| 149 |
GPR_ASSERT(num_threads_ == 0); |
| 150 |
gpr_atm_rel_store(&num_threads_, 1); |
| 151 |
thd_state_ = static_cast<ThreadState*>( |
| 152 |
gpr_zalloc(sizeof(ThreadState) * max_threads_)); |
| 153 |
|
| 154 |
for (size_t i = 0; i < max_threads_; i++) { |
| 155 |
gpr_mu_init(&thd_state_[i].mu); |
| 156 |
gpr_cv_init(&thd_state_[i].cv); |
| 157 |
thd_state_[i].id = i; |
| 158 |
thd_state_[i].name = name_; |
| 159 |
thd_state_[i].thd = Thread(); |
| 160 |
thd_state_[i].elems = GRPC_CLOSURE_LIST_INIT; |
| 161 |
} |
| 162 |
|
| 163 |
thd_state_[0].thd = Thread(name_, &Executor::ThreadMain, &thd_state_[0]); |
| 164 |
thd_state_[0].thd.Start(); |
| 165 |
} else { // !threading |
| 166 |
if (curr_num_threads == 0) { |
| 167 |
EXECUTOR_TRACE("(%s) SetThreading(false). curr_num_threads == 0", name_); |
| 168 |
return; |
| 169 |
} |
| 170 |
|
| 171 |
for (size_t i = 0; i < max_threads_; i++) { |
| 172 |
gpr_mu_lock(&thd_state_[i].mu); |
| 173 |
thd_state_[i].shutdown = true; |
| 174 |
gpr_cv_signal(&thd_state_[i].cv); |
| 175 |
gpr_mu_unlock(&thd_state_[i].mu); |
| 176 |
} |
| 177 |
|
| 178 |
/* Ensure no thread is adding a new thread. Once this is past, then no |
| 179 |
* thread will try to add a new one either (since shutdown is true) */ |
| 180 |
gpr_spinlock_lock(&adding_thread_lock_); |
| 181 |
gpr_spinlock_unlock(&adding_thread_lock_); |
| 182 |
|
| 183 |
curr_num_threads = gpr_atm_no_barrier_load(&num_threads_); |
| 184 |
for (gpr_atm i = 0; i < curr_num_threads; i++) { |
| 185 |
thd_state_[i].thd.Join(); |
| 186 |
EXECUTOR_TRACE("(%s) Thread %" PRIdPTR " of %" PRIdPTR " joined", name_, |
| 187 |
i + 1, curr_num_threads); |
| 188 |
} |
| 189 |
|
| 190 |
gpr_atm_rel_store(&num_threads_, 0); |
| 191 |
for (size_t i = 0; i < max_threads_; i++) { |
| 192 |
gpr_mu_destroy(&thd_state_[i].mu); |
| 193 |
gpr_cv_destroy(&thd_state_[i].cv); |
| 194 |
RunClosures(thd_state_[i].name, thd_state_[i].elems); |
| 195 |
} |
| 196 |
|
| 197 |
gpr_free(thd_state_); |
| 198 |
|
| 199 |
// grpc_iomgr_shutdown_background_closure() will close all the registered |
| 200 |
// fds in the background poller, and wait for all pending closures to |
| 201 |
// finish. Thus, never call Executor::SetThreading(false) in the middle of |
| 202 |
// an application. |
| 203 |
// TODO(guantaol): create another method to finish all the pending closures |
| 204 |
// registered in the background poller by Executor. |
| 205 |
grpc_iomgr_platform_shutdown_background_closure(); |
| 206 |
} |
| 207 |
|
| 208 |
EXECUTOR_TRACE("(%s) SetThreading(%d) done", name_, threading); |
| 209 |
} |
| 210 |
|
| 211 |
void Executor::Shutdown() { SetThreading(false); } |
| 212 |
|
| 213 |
void Executor::ThreadMain(void* arg) { |
| 214 |
ThreadState* ts = static_cast<ThreadState*>(arg); |
| 215 |
g_this_thread_state = ts; |
| 216 |
|
| 217 |
ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); |
| 218 |
|
| 219 |
size_t subtract_depth = 0; |
| 220 |
for (;;) { |
| 221 |
EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: step (sub_depth=%" PRIdPTR ")", |
| 222 |
ts->name, ts->id, subtract_depth); |
| 223 |
|
| 224 |
gpr_mu_lock(&ts->mu); |
| 225 |
ts->depth -= subtract_depth; |
| 226 |
// Wait for closures to be enqueued or for the executor to be shutdown |
| 227 |
while (grpc_closure_list_empty(ts->elems) && !ts->shutdown) { |
| 228 |
ts->queued_long_job = false; |
| 229 |
gpr_cv_wait(&ts->cv, &ts->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC)); |
| 230 |
} |
| 231 |
|
| 232 |
if (ts->shutdown) { |
| 233 |
EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: shutdown", ts->name, ts->id); |
| 234 |
gpr_mu_unlock(&ts->mu); |
| 235 |
break; |
| 236 |
} |
| 237 |
|
| 238 |
grpc_closure_list closures = ts->elems; |
| 239 |
ts->elems = GRPC_CLOSURE_LIST_INIT; |
| 240 |
gpr_mu_unlock(&ts->mu); |
| 241 |
|
| 242 |
EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: execute", ts->name, ts->id); |
| 243 |
|
| 244 |
ExecCtx::Get()->InvalidateNow(); |
| 245 |
subtract_depth = RunClosures(ts->name, closures); |
| 246 |
} |
| 247 |
|
| 248 |
g_this_thread_state = nullptr; |
| 249 |
} |
| 250 |
|
| 251 |
void Executor::Enqueue(grpc_closure* closure, grpc_error_handle error, |
| 252 |
bool is_short) { |
| 253 |
bool retry_push; |
| 254 |
|
| 255 |
do { |
| 256 |
retry_push = false; |
| 257 |
size_t cur_thread_count = |
| 258 |
static_cast<size_t>(gpr_atm_acq_load(&num_threads_)); |
| 259 |
|
| 260 |
// If the number of threads is zero(i.e either the executor is not threaded |
| 261 |
// or already shutdown), then queue the closure on the exec context itself |
| 262 |
if (cur_thread_count == 0) { |
| 263 |
#ifndef NDEBUG |
| 264 |
EXECUTOR_TRACE("(%s) schedule %p (created %s:%d) inline", name_, closure, |
| 265 |
closure->file_created, closure->line_created); |
| 266 |
#else |
| 267 |
EXECUTOR_TRACE("(%s) schedule %p inline", name_, closure); |
| 268 |
#endif |
| 269 |
grpc_closure_list_append(ExecCtx::Get()->closure_list(), closure, error); |
| 270 |
return; |
| 271 |
} |
| 272 |
|
| 273 |
if (grpc_iomgr_platform_add_closure_to_background_poller(closure, error)) { |
| 274 |
return; |
| 275 |
} |
| 276 |
|
| 277 |
ThreadState* ts = g_this_thread_state; |
| 278 |
if (ts == nullptr) { |
| 279 |
ts = &thd_state_[HashPointer(ExecCtx::Get(), cur_thread_count)]; |
| 280 |
} |
| 281 |
|
| 282 |
ThreadState* orig_ts = ts; |
| 283 |
bool try_new_thread = false; |
| 284 |
|
| 285 |
for (;;) { |
| 286 |
#ifndef NDEBUG |
| 287 |
EXECUTOR_TRACE( |
| 288 |
"(%s) try to schedule %p (%s) (created %s:%d) to thread " |
| 289 |
"%" PRIdPTR, |
| 290 |
name_, closure, is_short ? "short" : "long", closure->file_created, |
| 291 |
closure->line_created, ts->id); |
| 292 |
#else |
| 293 |
EXECUTOR_TRACE("(%s) try to schedule %p (%s) to thread %" PRIdPTR, name_, |
| 294 |
closure, is_short ? "short" : "long", ts->id); |
| 295 |
#endif |
| 296 |
|
| 297 |
gpr_mu_lock(&ts->mu); |
| 298 |
if (ts->queued_long_job) { |
| 299 |
// if there's a long job queued, we never queue anything else to this |
| 300 |
// queue (since long jobs can take 'infinite' time and we need to |
| 301 |
// guarantee no starvation). Spin through queues and try again |
| 302 |
gpr_mu_unlock(&ts->mu); |
| 303 |
size_t idx = ts->id; |
| 304 |
ts = &thd_state_[(idx + 1) % cur_thread_count]; |
| 305 |
if (ts == orig_ts) { |
| 306 |
// We cycled through all the threads. Retry enqueue again by creating |
| 307 |
// a new thread |
| 308 |
// |
| 309 |
// TODO (sreek): There is a potential issue here. We are |
| 310 |
// unconditionally setting try_new_thread to true here. What if the |
| 311 |
// executor is shutdown OR if cur_thread_count is already equal to |
| 312 |
// max_threads ? |
| 313 |
// (Fortunately, this is not an issue yet (as of july 2018) because |
| 314 |
// there is only one instance of long job in gRPC and hence we will |
| 315 |
// not hit this code path) |
| 316 |
retry_push = true; |
| 317 |
try_new_thread = true; |
| 318 |
break; |
| 319 |
} |
| 320 |
|
| 321 |
continue; // Try the next thread-state |
| 322 |
} |
| 323 |
|
| 324 |
// == Found the thread state (i.e thread) to enqueue this closure! == |
| 325 |
|
| 326 |
// Also, if this thread has been waiting for closures, wake it up. |
| 327 |
// - If grpc_closure_list_empty() is true and the Executor is not |
| 328 |
// shutdown, it means that the thread must be waiting in ThreadMain() |
| 329 |
// - Note that gpr_cv_signal() won't immediately wakeup the thread. That |
| 330 |
// happens after we release the mutex &ts->mu a few lines below |
| 331 |
if (grpc_closure_list_empty(ts->elems) && !ts->shutdown) { |
| 332 |
gpr_cv_signal(&ts->cv); |
| 333 |
} |
| 334 |
|
| 335 |
grpc_closure_list_append(&ts->elems, closure, error); |
| 336 |
|
| 337 |
// If we already queued more than MAX_DEPTH number of closures on this |
| 338 |
// thread, use this as a hint to create more threads |
| 339 |
ts->depth++; |
| 340 |
try_new_thread = ts->depth > MAX_DEPTH && |
| 341 |
cur_thread_count < max_threads_ && !ts->shutdown; |
| 342 |
|
| 343 |
ts->queued_long_job = !is_short; |
| 344 |
|
| 345 |
gpr_mu_unlock(&ts->mu); |
| 346 |
break; |
| 347 |
} |
| 348 |
|
| 349 |
if (try_new_thread && gpr_spinlock_trylock(&adding_thread_lock_)) { |
| 350 |
cur_thread_count = static_cast<size_t>(gpr_atm_acq_load(&num_threads_)); |
| 351 |
if (cur_thread_count < max_threads_) { |
| 352 |
// Increment num_threads (safe to do a store instead of a cas because we |
| 353 |
// always increment num_threads under the 'adding_thread_lock') |
| 354 |
gpr_atm_rel_store(&num_threads_, cur_thread_count + 1); |
| 355 |
|
| 356 |
thd_state_[cur_thread_count].thd = |
| 357 |
Thread(name_, &Executor::ThreadMain, &thd_state_[cur_thread_count]); |
| 358 |
thd_state_[cur_thread_count].thd.Start(); |
| 359 |
} |
| 360 |
gpr_spinlock_unlock(&adding_thread_lock_); |
| 361 |
} |
| 362 |
} while (retry_push); |
| 363 |
} |
| 364 |
|
| 365 |
// Executor::InitAll() and Executor::ShutdownAll() functions are called in the |
| 366 |
// the grpc_init() and grpc_shutdown() code paths which are protected by a |
| 367 |
// global mutex. So it is okay to assume that these functions are thread-safe |
| 368 |
void Executor::InitAll() { |
| 369 |
EXECUTOR_TRACE0("Executor::InitAll() enter"); |
| 370 |
|
| 371 |
// Return if Executor::InitAll() is already called earlier |
| 372 |
if (executors[static_cast<size_t>(ExecutorType::DEFAULT)] != nullptr) { |
| 373 |
GPR_ASSERT(executors[static_cast<size_t>(ExecutorType::RESOLVER)] != |
| 374 |
nullptr); |
| 375 |
return; |
| 376 |
} |
| 377 |
|
| 378 |
executors[static_cast<size_t>(ExecutorType::DEFAULT)] = |
| 379 |
new Executor("default-executor"); |
| 380 |
executors[static_cast<size_t>(ExecutorType::RESOLVER)] = |
| 381 |
new Executor("resolver-executor"); |
| 382 |
|
| 383 |
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Init(); |
| 384 |
executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Init(); |
| 385 |
|
| 386 |
EXECUTOR_TRACE0("Executor::InitAll() done"); |
| 387 |
} |
| 388 |
|
| 389 |
void Executor::Run(grpc_closure* closure, grpc_error_handle error, |
| 390 |
ExecutorType executor_type, ExecutorJobType job_type) { |
| 391 |
executor_enqueue_fns_[static_cast<size_t>(executor_type)] |
| 392 |
[static_cast<size_t>(job_type)](closure, error); |
| 393 |
} |
| 394 |
|
| 395 |
void Executor::ShutdownAll() { |
| 396 |
EXECUTOR_TRACE0("Executor::ShutdownAll() enter"); |
| 397 |
|
| 398 |
// Return if Executor:SshutdownAll() is already called earlier |
| 399 |
if (executors[static_cast<size_t>(ExecutorType::DEFAULT)] == nullptr) { |
| 400 |
GPR_ASSERT(executors[static_cast<size_t>(ExecutorType::RESOLVER)] == |
| 401 |
nullptr); |
| 402 |
return; |
| 403 |
} |
| 404 |
|
| 405 |
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Shutdown(); |
| 406 |
executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Shutdown(); |
| 407 |
|
| 408 |
// Delete the executor objects. |
| 409 |
// |
| 410 |
// NOTE: It is important to call Shutdown() on all executors first before |
| 411 |
// calling delete because it is possible for one executor (that is not |
| 412 |
// shutdown yet) to call Enqueue() on a different executor which is already |
| 413 |
// shutdown. This is legal and in such cases, the Enqueue() operation |
| 414 |
// effectively "fails" and enqueues that closure on the calling thread's |
| 415 |
// exec_ctx. |
| 416 |
// |
| 417 |
// By ensuring that all executors are shutdown first, we are also ensuring |
| 418 |
// that no thread is active across all executors. |
| 419 |
|
| 420 |
delete executors[static_cast<size_t>(ExecutorType::DEFAULT)]; |
| 421 |
delete executors[static_cast<size_t>(ExecutorType::RESOLVER)]; |
| 422 |
executors[static_cast<size_t>(ExecutorType::DEFAULT)] = nullptr; |
| 423 |
executors[static_cast<size_t>(ExecutorType::RESOLVER)] = nullptr; |
| 424 |
|
| 425 |
EXECUTOR_TRACE0("Executor::ShutdownAll() done"); |
| 426 |
} |
| 427 |
|
| 428 |
bool Executor::IsThreaded(ExecutorType executor_type) { |
| 429 |
GPR_ASSERT(executor_type < ExecutorType::NUM_EXECUTORS); |
| 430 |
return executors[static_cast<size_t>(executor_type)]->IsThreaded(); |
| 431 |
} |
| 432 |
|
| 433 |
bool Executor::IsThreadedDefault() { |
| 434 |
return Executor::IsThreaded(ExecutorType::DEFAULT); |
| 435 |
} |
| 436 |
|
| 437 |
void Executor::SetThreadingAll(bool enable) { |
| 438 |
EXECUTOR_TRACE("Executor::SetThreadingAll(%d) called", enable); |
| 439 |
for (size_t i = 0; i < static_cast<size_t>(ExecutorType::NUM_EXECUTORS); |
| 440 |
i++) { |
| 441 |
executors[i]->SetThreading(enable); |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
void Executor::SetThreadingDefault(bool enable) { |
| 446 |
EXECUTOR_TRACE("Executor::SetThreadingDefault(%d) called", enable); |
| 447 |
executors[static_cast<size_t>(ExecutorType::DEFAULT)]->SetThreading(enable); |
| 448 |
} |
| 449 |
|
| 450 |
} // namespace grpc_core |