• 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 #ifndef OHOS_APPEXECFWK_TASK_EXECUTOR_H
16 #define OHOS_APPEXECFWK_TASK_EXECUTOR_H
17 
18 #include <atomic>
19 #include <mutex>
20 #include <thread>
21 
22 #include "appexecfwk_errors.h"
23 
24 #include "blocking_queue.h"
25 #include "delay_execute_service.h"
26 #include "delay_queue.h"
27 #include "task.h"
28 #include "work_thread.h"
29 #include "worker_pool.h"
30 
31 namespace OHOS {
32 namespace AppExecFwk {
33 class TaskExecutor : public WorkerPool,
34                      public DelayExecuteService,
35                      public Delegate,
36                      public std::enable_shared_from_this<TaskExecutor> {
37 public:
38     TaskExecutor(const std::shared_ptr<WorkerPoolConfig> &config);
39     virtual ~TaskExecutor();
40 
41     void Execute(const std::shared_ptr<Task> &task);
42 
43     ErrCode DoWorks(const std::shared_ptr<WorkerThread> &worker) override;
44 
45     void Terminate(bool force);
46 
47     bool DelayExecute(const Runnable &runnable, long delayMs) override;
48 
49     int GetPendingTasksSize();
50 
51     long GetTaskCounter();
52 
53 protected:
54     void AfterRun(const std::shared_ptr<Task> &task) override;
55     void BeforeRun(const std::shared_ptr<Task> &task) override;
56 
57 private:
58     std::shared_ptr<Task> GetTask(const std::shared_ptr<WorkerThread> &workerThread);
59 
60     void TerminateConsumer();
61 
62     bool EnsureConsumeStarted();
63 
64     void Consume();
65 
66     long GetAndIncrement(std::atomic<long> &atomiclong);
67 
68     long IncrementAndGet(std::atomic<long> &atomiclong);
69 
70 private:
71     static std::atomic<long> sequence;
72 
73     std::shared_ptr<DelayQueue> delayTasks_;
74 
75     std::shared_ptr<std::thread> consumer_;
76 
77     std::shared_ptr<BlockingQueue> pendingTasks_;
78 
79     std::atomic<bool> terminated_;
80 
81     std::atomic<long> taskCounter_;
82 
83     std::mutex dataMutex_;
84 };
85 }  // namespace AppExecFwk
86 }  // namespace OHOS
87 #endif