Apollo  v5.5.0
Open source self driving car software
thread_pool.h
Go to the documentation of this file.
1 /******************************************************************************
2  * Copyright 2018 The Apollo Authors. All Rights Reserved.
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 #pragma once
17 
18 #include <vector>
19 
20 #include "google/protobuf/stubs/common.h"
21 
25 
26 namespace apollo {
27 namespace perception {
28 namespace lib {
29 
30 class ThreadPoolWorker;
31 
32 class ThreadPool {
33  public:
34  explicit ThreadPool(int num_workers);
35 
36  ~ThreadPool();
37 
38  void Start();
39 
40  void Add(google::protobuf::Closure *closure);
41  void Add(const std::vector<google::protobuf::Closure *> &closures);
42 
43  int num_workers() const { return num_workers_; }
44 
45  int num_available_workers() const { return num_available_workers_; }
46 
47  ThreadPool(const ThreadPool &) = delete;
48  ThreadPool &operator=(const ThreadPool &) = delete;
49 
50  private:
51  friend class ThreadPoolWorker;
52 
53  std::vector<ThreadPoolWorker *> workers_;
54  int num_workers_;
55  int num_available_workers_;
56  Mutex mutex_;
57 
59  bool started_;
60 };
61 
62 class ThreadPoolWorker : public Thread {
63  public:
64  explicit ThreadPoolWorker(ThreadPool *thread_pool)
65  : Thread(true, "ThreadPoolWorker"), thread_pool_(thread_pool) {}
66 
67  virtual ~ThreadPoolWorker() {}
68 
69  ThreadPoolWorker(const ThreadPoolWorker &) = delete;
70  ThreadPoolWorker &operator=(const ThreadPoolWorker &) = delete;
71 
72  protected:
73  void Run() override;
74 
75  private:
76  ThreadPool *thread_pool_;
77 };
78 
79 } // namespace lib
80 } // namespace perception
81 } // namespace apollo
Definition: thread_pool.h:32
void Add(google::protobuf::Closure *closure)
Definition: blob.h:72
Definition: mutex.h:24
virtual ~ThreadPoolWorker()
Definition: thread_pool.h:67
ThreadPoolWorker(ThreadPool *thread_pool)
Definition: thread_pool.h:64
Definition: thread.h:24
friend class ThreadPoolWorker
Definition: thread_pool.h:51
Definition: concurrent_queue.h:89
int num_available_workers() const
Definition: thread_pool.h:45
int num_workers() const
Definition: thread_pool.h:43
ThreadPool & operator=(const ThreadPool &)=delete
Definition: thread_pool.h:62