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 
16 #ifndef TASK_POOL_IMPL_H
17 #define TASK_POOL_IMPL_H
18 
19 #include <condition_variable>
20 #include <map>
21 #include <mutex>
22 #include <string>
23 #include <thread>
24 
25 #include "task_pool.h"
26 #include "task_queue.h"
27 
28 namespace DistributedDB {
29 class TaskPoolImpl : public TaskPool {
30 public:
31     // maxThreads > 0.
32     TaskPoolImpl(int maxThreads, int minThreads);
33 
34     // Start the task pool.
35     int Start() override;
36 
37     // Stop the task pool.
38     void Stop() override;
39 
40     // Schedule a task, the task can be ran in any thread.
41     int Schedule(const Task &task) override;
42 
43     // Schedule tasks one by one.
44     int Schedule(const std::string &queueTag, const Task &task) override;
45 
46     // Shrink memory associated with the given tag if possible.
47     void ShrinkMemory(const std::string &tag) override;
48 
49 protected:
50     ~TaskPoolImpl();
51 
52 private:
53     int SpawnThreads(bool isStart);
54     bool IdleExit(std::unique_lock<std::mutex> &lock);
55     void SetThreadFree();
56     Task ReapTask(TaskQueue *&queue);
57     void GetTask(Task &task, TaskQueue *&queue);
58     bool IsGenericWorker() const;
59     void BecomeGenericWorker();
60     void ExitWorker();
61     void TaskWorker();
62     void FinishExecuteTask(TaskQueue *taskQueue);
63     void TryToSpawnThreads();
64     bool IsExecutingTasksEmpty() const;
65 
66     // Member Variables.
67     static constexpr int IDLE_WAIT_PERIOD = 1;  // wait 1 second before exiting.
68     std::mutex tasksMutex_;
69     std::condition_variable hasTasks_;
70     std::map<std::string, TaskQueue> queuedTasks_;
71     TaskQueue genericTasks_;
72     std::thread::id genericThread_;  // execute generic task only.
73     int genericTaskCount_;
74     int queuedTaskCount_;
75     bool isStarted_;
76     bool isStopping_;   // Stop() invoked.
77     std::condition_variable allThreadsExited_;
78 
79     // Thread counter.
80     int maxThreads_;
81     int minThreads_;
82     int curThreads_;
83     int idleThreads_;
84 };
85 } // namespace DistributedDB
86 
87 #endif // TASK_POOL_IMPL_H
88