7 #include <packager/file/thread_pool.h>
11 #include <absl/log/check.h>
12 #include <absl/log/log.h>
13 #include <absl/time/time.h>
19 const absl::Duration kMaxThreadIdleTime = absl::Minutes(10);
24 ThreadPool ThreadPool::instance;
26 ThreadPool::ThreadPool() : num_idle_threads_(0), terminated_(false) {}
28 ThreadPool::~ThreadPool() {
32 void ThreadPool::PostTask(
const std::function<
void()>& task) {
33 absl::MutexLock lock(&mutex_);
35 DCHECK(!terminated_) <<
"Should not call PostTask after Terminate!";
44 DLOG(ERROR) <<
"Should not post an empty task!";
48 tasks_.push(std::move(task));
50 if (num_idle_threads_ >= tasks_.size()) {
52 tasks_available_.SignalAll();
55 std::thread thread(std::bind(&ThreadPool::ThreadMain,
this));
60 void ThreadPool::Terminate() {
62 absl::MutexLock lock(&mutex_);
64 while (!tasks_.empty()) {
68 tasks_available_.SignalAll();
71 ThreadPool::Task ThreadPool::WaitForTask() {
72 absl::MutexLock lock(&mutex_);
81 tasks_available_.WaitWithTimeout(&mutex_, kMaxThreadIdleTime);
91 Task task = tasks_.front();
96 void ThreadPool::ThreadMain() {
98 auto task = WaitForTask();
All the methods that are virtual are virtual for mocking.