From b1663e74657d045e6f35b87bcea107e68767345f Mon Sep 17 00:00:00 2001
From: Craig Tiller <craig.tiller@gmail.com>
Date: Sun, 1 Feb 2015 22:09:38 -0800
Subject: [PATCH] Remove a major source of contention in thread_pool

- notify_one when new work is available to avoid thundering herd
  problems
- checking conditions before entering cv_.wait() prevents a case that
  these are not validated
---
 src/cpp/server/thread_pool.cc | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/src/cpp/server/thread_pool.cc b/src/cpp/server/thread_pool.cc
index a46d4c64d2..35d61244f2 100644
--- a/src/cpp/server/thread_pool.cc
+++ b/src/cpp/server/thread_pool.cc
@@ -41,7 +41,8 @@ ThreadPool::ThreadPool(int num_threads) {
       for (;;) {
         std::unique_lock<std::mutex> lock(mu_);
         // Wait until work is available or we are shutting down.
-        cv_.wait(lock, [=]() { return shutdown_ || !callbacks_.empty(); });
+        if (!shutdown_ || callbacks_.empty())
+          cv_.wait(lock, [=]() { return shutdown_ || !callbacks_.empty(); });
         // Drain callbacks before considering shutdown to ensure all work
         // gets completed.
         if (!callbacks_.empty()) {
@@ -71,7 +72,7 @@ ThreadPool::~ThreadPool() {
 void ThreadPool::ScheduleCallback(const std::function<void()> &callback) {
   std::lock_guard<std::mutex> lock(mu_);
   callbacks_.push(callback);
-  cv_.notify_all();
+  cv_.notify_one();
 }
 
 }  // namespace grpc
-- 
GitLab