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