blob: a00f2be8e8928e52d140c1e25bfe687b96fa2cd6 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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
25#include "absl/base/thread_annotations.h"
26#include "absl/synchronization/mutex.h"
27
28namespace absl {
29namespace synchronization_internal {
30
31// A simple ThreadPool implementation for tests.
32class 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
43 ~ThreadPool() {
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:
63 bool WorkAvailable() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
64 return !queue_.empty();
65 }
66
67 void WorkLoop() {
68 while (true) {
69 std::function<void()> func;
70 {
71 absl::MutexLock l(&mu_);
72 mu_.Await(absl::Condition(this, &ThreadPool::WorkAvailable));
73 func = std::move(queue_.front());
74 queue_.pop();
75 }
76 if (func == nullptr) { // Shutdown signal.
77 break;
78 }
79 func();
80 }
81 }
82
83 absl::Mutex mu_;
84 std::queue<std::function<void()>> queue_ ABSL_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_