gRPC DynamicThreadPool可以并行执行任务吗?

时间:2020-11-04 06:32:54

标签: multithreading threadpool grpc

在gRPC C ++源代码中,其线程函数 DynamicThreadPool :: DynamicThread :: ThreadFunc()在每个线程中执行。但是此函数调用属于线程池的 DynamicThreadPool :: ThreadFunc()。在 DynamicThreadPool :: ThreadFunc()中,在执行一些工作之前,它将先调用 grpc_core :: ReleasableMutexLock lock(&mu _)进行锁定。因此,似乎线程池中的任务总是按顺序执行。我会误会吗?如果没有,使用多线程有什么好处?

void DynamicThreadPool::DynamicThread::ThreadFunc() {
  pool_->ThreadFunc();
  // Now that we have killed ourselves, we should reduce the thread count
  grpc_core::MutexLock lock(&pool_->mu_);
  pool_->nthreads_--;
  // Move ourselves to dead list
  pool_->dead_threads_.push_back(this);

  if ((pool_->shutdown_) && (pool_->nthreads_ == 0)) {
    pool_->shutdown_cv_.Signal();
  }
}

void DynamicThreadPool::ThreadFunc() {
  for (;;) {
    // Wait until work is available or we are shutting down.
    grpc_core::ReleasableMutexLock lock(&mu_);
    if (!shutdown_ && callbacks_.empty()) {
      // If there are too many threads waiting, then quit this thread
      if (threads_waiting_ >= reserve_threads_) {
        break;
      }
      threads_waiting_++;
      cv_.Wait(&mu_);
      threads_waiting_--;
    }
    // Drain callbacks before considering shutdown to ensure all work
    // gets completed.
    if (!callbacks_.empty()) {
      auto cb = callbacks_.front();
      callbacks_.pop();
      lock.Unlock();
      cb();
    } else if (shutdown_) {
      break;
    }
  }
}

0 个答案:

没有答案