TensorFlow Serving C++ API Documentation
fixed_thread_pool.h
1 /* Copyright 2018 Google Inc. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7  http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_SERVING_UTIL_NET_HTTP_INTERNAL_FIXED_THREAD_POOL_H_
17 #define TENSORFLOW_SERVING_UTIL_NET_HTTP_INTERNAL_FIXED_THREAD_POOL_H_
18 
19 #include <cassert>
20 #include <functional>
21 #include <queue>
22 #include <thread> // NOLINT(build/c++11)
23 #include <vector>
24 
25 #include "absl/base/thread_annotations.h"
26 #include "absl/synchronization/mutex.h"
27 
28 namespace tensorflow {
29 namespace serving {
30 namespace net_http {
31 
32 // A simple fixed-size ThreadPool implementation for tests.
33 // The initial version is copied from
34 // absl/synchronization/internal/thread_pool.h
36  public:
37  explicit FixedThreadPool(int num_threads) {
38  for (int i = 0; i < num_threads; ++i) {
39  threads_.push_back(std::thread(&FixedThreadPool::WorkLoop, this));
40  }
41  }
42 
43  FixedThreadPool(const FixedThreadPool &) = delete;
44  FixedThreadPool &operator=(const FixedThreadPool &) = delete;
45 
46  ~FixedThreadPool() {
47  {
48  absl::MutexLock l(&mu_);
49  for (int i = 0; i < threads_.size(); ++i) {
50  queue_.push(nullptr); // Shutdown signal.
51  }
52  }
53  for (auto &t : threads_) {
54  t.join();
55  }
56  }
57 
58  // Schedule a function to be run on a ThreadPool thread immediately.
59  void Schedule(std::function<void()> func) {
60  assert(func != nullptr);
61  absl::MutexLock l(&mu_);
62  queue_.push(std::move(func));
63  }
64 
65  private:
66  bool WorkAvailable() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
67  return !queue_.empty();
68  }
69 
70  void WorkLoop() {
71  while (true) {
72  std::function<void()> func;
73  {
74  absl::MutexLock l(&mu_);
75  mu_.Await(absl::Condition(this, &FixedThreadPool::WorkAvailable));
76  func = std::move(queue_.front());
77  queue_.pop();
78  }
79  if (func == nullptr) { // Shutdown signal.
80  break;
81  }
82  func();
83  }
84  }
85 
86  absl::Mutex mu_;
87  std::queue<std::function<void()>> queue_ ABSL_GUARDED_BY(mu_);
88  std::vector<std::thread> threads_;
89 };
90 
91 } // namespace net_http
92 } // namespace serving
93 } // namespace tensorflow
94 
95 #endif // TENSORFLOW_SERVING_UTIL_NET_HTTP_INTERNAL_FIXED_THREAD_POOL_H_