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