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 FOUNDATION_ACE_FRAMEWORKS_BASE_THREAD_BACKGROUND_TASK_EXECUTOR_H 17 #define FOUNDATION_ACE_FRAMEWORKS_BASE_THREAD_BACKGROUND_TASK_EXECUTOR_H 18 19 #include <condition_variable> 20 #include <functional> 21 #include <list> 22 #include <mutex> 23 #include <thread> 24 25 #include "base/utils/noncopyable.h" 26 27 namespace OHOS::Ace { 28 29 enum class BgTaskPriority { 30 DEFAULT, 31 LOW, 32 }; 33 34 class BackgroundTaskExecutor { 35 ACE_DISALLOW_COPY_AND_MOVE(BackgroundTaskExecutor); 36 37 public: 38 using Task = std::function<void()>; 39 40 static BackgroundTaskExecutor& GetInstance(); 41 42 bool PostTask(Task&& task, BgTaskPriority priority = BgTaskPriority::DEFAULT); 43 bool PostTask(const Task& task, BgTaskPriority priority = BgTaskPriority::DEFAULT); 44 45 void TriggerGarbageCollection(); 46 47 private: 48 BackgroundTaskExecutor(); 49 ~BackgroundTaskExecutor(); 50 51 void StartNewThreads(size_t num = 1); 52 void ThreadLoop(uint32_t threadNo); 53 54 std::mutex mutex_; 55 std::condition_variable condition_; 56 std::list<Task> tasks_; 57 std::list<Task> lowPriorityTasks_; 58 std::list<std::thread> threads_; 59 size_t currentThreadNum_ { 0 }; 60 size_t maxThreadNum_ { 0 }; 61 bool running_ { true }; 62 uint32_t purgeFlags_ { 0 }; 63 }; 64 65 } // namespace OHOS::Ace 66 67 #endif // FOUNDATION_ACE_FRAMEWORKS_BASE_THREAD_BACKGROUND_TASK_EXECUTOR_H 68