• 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 
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     int 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 
65     // Member Variables.
66     static constexpr int IDLE_WAIT_PERIOD = 1;  // wait 1 second before exiting.
67     std::mutex tasksMutex_;
68     std::condition_variable hasTasks_;
69     std::map<std::string, TaskQueue> queuedTasks_;
70     TaskQueue genericTasks_;
71     std::thread::id genericThread_;  // execute generic task only.
72     int genericTaskCount_;
73     int queuedTaskCount_;
74     bool isStarted_;
75     bool isStopping_;   // Stop() invoked.
76     std::condition_variable allThreadsExited_;
77 
78     // Thread counter.
79     int maxThreads_;
80     int minThreads_;
81     int curThreads_;
82     int idleThreads_;
83 };
84 } // namespace DistributedDB
85 
86 #endif // TASK_POOL_IMPL_H
87