client-cpp  0.9.0
ThreadPool.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2014-2016 CyberVision, Inc.
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 
17 #ifndef THREADPOOL_HPP_
18 #define THREADPOOL_HPP_
19 
20 #include <atomic>
21 #include <cstdlib>
22 #include <vector>
23 #include <thread>
24 
25 #include "kaa/KaaThread.hpp"
26 #include "kaa/utils/KaaTimer.hpp"
28 
29 namespace kaa {
30 
31 class ThreadPool : public IThreadPool {
32  friend class Worker;
33 
34 public:
35  ThreadPool(std::size_t workerCount = DEFAULT_WORKER_NUMBER);
36  ~ThreadPool();
37 
38  virtual void add(const ThreadPoolTask& task);
39 
40  virtual void awaitTermination(std::size_t seconds);
41 
42  virtual void shutdown();
43  virtual void shutdownNow();
44 
45 public:
46  static const std::size_t DEFAULT_WORKER_NUMBER = 1;
47 
48 private:
49  void start();
50  void stop(bool force);
51 
52 private:
53  bool isRun_ = true;
54  bool isPendingShutdown_ = false;
55 
56  std::list<std::thread> workers_;
57  std::size_t workerCount_ = 0;
58 
59  std::list<ThreadPoolTask> tasks_;
60 
61  KAA_MUTEX_DECLARE(threadPoolGuard_);
62  KAA_CONDITION_VARIABLE onNewTask_;
63 
64  std::unique_ptr<KaaTimer<void()>> shutdownTimer_;
65 };
66 
67 } /* namespace kaa */
68 
69 #endif /* THREADPOOL_HPP_ */
static const std::size_t DEFAULT_WORKER_NUMBER
Definition: ThreadPool.hpp:46
#define KAA_CONDITION_VARIABLE
Definition: KaaThread.hpp:37
virtual void add(const ThreadPoolTask &task)
#define KAA_MUTEX_DECLARE(name)
Definition: KaaThread.hpp:44
friend class Worker
Definition: ThreadPool.hpp:32
virtual void awaitTermination(std::size_t seconds)
virtual void shutdownNow()
ThreadPool(std::size_t workerCount=DEFAULT_WORKER_NUMBER)
std::function< void()> ThreadPoolTask
Definition: IThreadPool.hpp:26
virtual void shutdown()