• 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 class ThreadPool : public NoCopyable {
31 public:
32     typedef std::function<void()> Task;
33 
34     // The name(args here) will be set as a part the real name of threads in pool.
35     // The real name of threads in pool will be like: myName_ + no.
36     // The thread name is a meaningful C language string, whose length
37     // is restricted to 16 characters, including the terminating null byte ('\0').
38     // Please pay attention to the length of name(args here).
39     explicit ThreadPool(const std::string &name = std::string());
40     ~ThreadPool();
41 
42     uint32_t Start(int threadsNum);
43     void Stop();
44     void AddTask(const Task& f);
SetMaxTaskNum(int maxSize)45     void SetMaxTaskNum(int maxSize) { maxTaskNum_ = maxSize; }
46 
47     // for testability
GetMaxTaskNum()48     size_t GetMaxTaskNum() const { return maxTaskNum_; }
49     size_t GetCurTaskNum();
GetThreadsNum()50     size_t GetThreadsNum() const { return threads_.size(); }
GetName()51     std::string GetName() const { return myName_; }
52 
53 private:
54     // tasks in the queue reach the maximum set by maxQueueSize, means thread pool is full load.
55     bool Overloaded() const;
56     void WorkInThread(); // main        function in each thread.
57     Task ScheduleTask(); // fetch a task from the queue and execute
58 
59 private:
60     std::string myName_;
61     std::mutex mutex_;
62     std::condition_variable hasTaskToDo_;
63     std::condition_variable acceptNewTask_;
64     std::vector<std::thread> threads_;
65     std::deque<Task> tasks_;
66     size_t maxTaskNum_;
67     bool running_;
68 };
69 
70 } // namespace OHOS
71 
72 #endif
73 
74