thread_pool.h
Go to the documentation of this file.
1 // Copyright 2017 The Abseil Authors.
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 // https://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 #ifndef ABSL_SYNCHRONIZATION_INTERNAL_THREAD_POOL_H_
16 #define ABSL_SYNCHRONIZATION_INTERNAL_THREAD_POOL_H_
17 
18 #include <cassert>
19 #include <cstddef>
20 #include <functional>
21 #include <queue>
22 #include <thread> // NOLINT(build/c++11)
23 #include <vector>
24 
27 
28 namespace absl {
29 namespace synchronization_internal {
30 
31 // A simple ThreadPool implementation for tests.
32 class ThreadPool {
33  public:
34  explicit ThreadPool(int num_threads) {
35  for (int i = 0; i < num_threads; ++i) {
36  threads_.push_back(std::thread(&ThreadPool::WorkLoop, this));
37  }
38  }
39 
40  ThreadPool(const ThreadPool &) = delete;
41  ThreadPool &operator=(const ThreadPool &) = delete;
42 
44  {
45  absl::MutexLock l(&mu_);
46  for (size_t i = 0; i < threads_.size(); i++) {
47  queue_.push(nullptr); // Shutdown signal.
48  }
49  }
50  for (auto &t : threads_) {
51  t.join();
52  }
53  }
54 
55  // Schedule a function to be run on a ThreadPool thread immediately.
56  void Schedule(std::function<void()> func) {
57  assert(func != nullptr);
58  absl::MutexLock l(&mu_);
59  queue_.push(std::move(func));
60  }
61 
62  private:
64  return !queue_.empty();
65  }
66 
67  void WorkLoop() {
68  while (true) {
69  std::function<void()> func;
70  {
71  absl::MutexLock l(&mu_);
73  func = std::move(queue_.front());
74  queue_.pop();
75  }
76  if (func == nullptr) { // Shutdown signal.
77  break;
78  }
79  func();
80  }
81  }
82 
84  std::queue<std::function<void()>> queue_ GUARDED_BY(mu_);
85  std::vector<std::thread> threads_;
86 };
87 
88 } // namespace synchronization_internal
89 } // namespace absl
90 
91 #endif // ABSL_SYNCHRONIZATION_INTERNAL_THREAD_POOL_H_
#define EXCLUSIVE_LOCKS_REQUIRED(...)
bool WorkAvailable() const EXCLUSIVE_LOCKS_REQUIRED(mu_)
Definition: thread_pool.h:63
std::queue< std::function< void()> > queue_ GUARDED_BY(mu_)
Definition: algorithm.h:29
ThreadPool & operator=(const ThreadPool &)=delete
std::vector< std::thread > threads_
Definition: thread_pool.h:85
void Await(const Condition &cond)
constexpr absl::remove_reference_t< T > && move(T &&t) noexcept
Definition: utility.h:219
void Schedule(std::function< void()> func)
Definition: thread_pool.h:56


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:19:58