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