client-cpp  0.10.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 <cstddef>
22 #include <thread>
23 
24 #include "kaa/KaaThread.hpp"
26 
27 namespace kaa {
28 
29 class ThreadPool : public IThreadPool {
30  friend class Worker;
31 
32 public:
33  ThreadPool(std::size_t workerCount = DEFAULT_WORKER_NUMBER);
34  ~ThreadPool();
35 
36  virtual void add(const ThreadPoolTask& task);
37 
38  virtual void awaitTermination(std::size_t seconds);
39 
40  virtual void shutdown();
41  virtual void shutdownNow();
42 
43 public:
44  static const std::size_t DEFAULT_WORKER_NUMBER = 1;
45 
46 private:
47  void start();
48  void stop();
49  void forceStop();
50  void waitForWorkersShutdown();
51 
52  enum class State {
53  CREATED,
54  RUNNING,
56  STOPPED,
57  };
58 
59 private:
60  State state_ = State::CREATED;
61 
62  std::list<std::thread> workers_;
63  std::size_t workerCount_ = 0;
64 
65  std::list<ThreadPoolTask> tasks_;
66 
67  KAA_MUTEX_DECLARE(threadPoolGuard_);
68  KAA_CONDITION_VARIABLE onThreadpoolEvent_;
69 };
70 
71 } /* namespace kaa */
72 
73 #endif /* THREADPOOL_HPP_ */
static const std::size_t DEFAULT_WORKER_NUMBER
Definition: ThreadPool.hpp:44
#define KAA_CONDITION_VARIABLE
Definition: KaaThread.hpp:37
virtual void add(const ThreadPoolTask &task)
Add a task for execution.
friend class Worker
Definition: ThreadPool.hpp:30
virtual void awaitTermination(std::size_t seconds)
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs...
virtual void shutdownNow()
Initiates a shutdown in which all executing tasks will complete. Pending tasks will be declined...
ThreadPool(std::size_t workerCount=DEFAULT_WORKER_NUMBER)
std::function< void()> ThreadPoolTask
Definition: IThreadPool.hpp:26
virtual void shutdown()
Initiates a shutdown in which previously added tasks are executed, but no new tasks will be accepted...