• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef THREAD_POOL_H
16 #define THREAD_POOL_H
17 
18 #include "nocopyable.h"
19 
20 #include <thread>
21 #include <mutex>
22 #include <functional>
23 #include <string>
24 #include <condition_variable>
25 #include <deque>
26 #include <vector>
27 
28 namespace OHOS {
29 
30 const int INVALID_SEMA_VALUE = -1;
31 
32 class ThreadPool : public NoCopyable {
33 public:
34     typedef std::function<void()> Task;
35 
36     explicit ThreadPool(const std::string &name = std::string());
37     ~ThreadPool();
38 
39     uint32_t Start(int threadsNum);
40     void Stop();
41     void AddTask(const Task& f);
SetMaxTaskNum(int maxSize)42     void SetMaxTaskNum(int maxSize) { maxTaskNum_ = maxSize; }
43 
44     // for testability
GetMaxTaskNum()45     size_t GetMaxTaskNum() const { return maxTaskNum_; }
46     size_t GetCurTaskNum();
GetThreadsNum()47     size_t GetThreadsNum() const { return threads_.size(); }
GetName()48     std::string GetName() const { return myName_; }
49 
50 private:
51     // tasks in the queue reach the maximum set by maxQueueSize, means thread pool is full load.
52     bool Overloaded() const;
53     void WorkInThread(); // main        function in each thread.
54     Task ScheduleTask(); // fetch a task from the queue and execute
55 
56 private:
57     std::string myName_;
58     std::mutex mutex_;
59     std::condition_variable hasTaskToDo_;
60     std::condition_variable acceptNewTask_;
61     std::vector<std::thread> threads_;
62     std::deque<Task> tasks_;
63     size_t maxTaskNum_;
64     bool running_;
65 };
66 
67 } // namespace OHOS
68 
69 #endif
70 
71