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