thread_pool.cc
Go to the documentation of this file.
1 /*
2  * Copyright 2016 The Cartographer Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
18 
19 #include <unistd.h>
20 #include <algorithm>
21 #include <chrono>
22 #include <numeric>
23 
24 #include "glog/logging.h"
25 
26 namespace cartographer {
27 namespace common {
28 
29 ThreadPool::ThreadPool(int num_threads) {
30  MutexLocker locker(&mutex_);
31  for (int i = 0; i != num_threads; ++i) {
32  pool_.emplace_back([this]() { ThreadPool::DoWork(); });
33  }
34 }
35 
37  {
38  MutexLocker locker(&mutex_);
39  CHECK(running_);
40  running_ = false;
41  CHECK_EQ(work_queue_.size(), 0);
42  }
43  for (std::thread& thread : pool_) {
44  thread.join();
45  }
46 }
47 
48 void ThreadPool::Schedule(std::function<void()> work_item) {
49  MutexLocker locker(&mutex_);
50  CHECK(running_);
51  work_queue_.push_back(work_item);
52 }
53 
55 #ifdef __linux__
56  // This changes the per-thread nice level of the current thread on Linux. We
57  // do this so that the background work done by the thread pool is not taking
58  // away CPU resources from more important foreground threads.
59  CHECK_NE(nice(10), -1);
60 #endif
61  for (;;) {
62  std::function<void()> work_item;
63  {
64  MutexLocker locker(&mutex_);
65  locker.Await([this]() REQUIRES(mutex_) {
66  return !work_queue_.empty() || !running_;
67  });
68  if (!work_queue_.empty()) {
69  work_item = work_queue_.front();
70  work_queue_.pop_front();
71  } else if (!running_) {
72  return;
73  }
74  }
75  CHECK(work_item);
76  work_item();
77  }
78 }
79 
80 } // namespace common
81 } // namespace cartographer
void Schedule(std::function< void()> work_item)
Definition: thread_pool.cc:48
#define REQUIRES(...)
Definition: mutex.h:44
Mutex::Locker MutexLocker
Definition: mutex.h:95


cartographer
Author(s):
autogenerated on Mon Jun 10 2019 12:51:39