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 OHOS_APP_DISPATCHER_THREADING_WORKER_THREAD_H 17 #define OHOS_APP_DISPATCHER_THREADING_WORKER_THREAD_H 18 19 #include <atomic> 20 21 #include "thread_factory.h" 22 #include "task.h" 23 #include "app_log_wrapper.h" 24 #include "appexecfwk_errors.h" 25 26 namespace OHOS { 27 namespace AppExecFwk { 28 29 class WorkerThread; 30 /** 31 * Interface for a work delegate. 32 */ 33 class Delegate { 34 public: 35 /** 36 * Do works for WorkerThread. 37 * 38 * @param worker is the thread-holder. 39 * 40 */ 41 virtual ErrCode DoWorks(const std::shared_ptr<WorkerThread> &worker) = 0; 42 }; 43 44 /** 45 * WorkerThread is a thread with a loop which can execute incoming tasks. 46 */ 47 class WorkerThread : public std::enable_shared_from_this<WorkerThread> { 48 public: 49 /** 50 * The construct function of the WorkerThread class. 51 * 52 * @param delegate delegates run works for this thread. 53 * @param firstTask if not null, take it as the first task in this thread. It can be null. 54 * @param factory can create a new thread which had some attributes set. 55 */ 56 WorkerThread(const std::shared_ptr<Delegate> &delegate, const std::shared_ptr<Task> &firstTask, 57 const std::shared_ptr<ThreadFactory> &factory); ~WorkerThread()58 virtual ~WorkerThread(){}; 59 60 void CreateThread(); 61 62 /** 63 * Increase the task counter of self. 64 * 65 */ 66 void IncTaskCount(void); 67 68 /** 69 * Gets the thread name. 70 * 71 * @return The thread name. 72 * 73 */ 74 std::string GetThreadName(void); 75 76 /** 77 * Get and remove |firstTask| of self. 78 * 79 * @return the |firstTask|. 80 * 81 */ 82 std::shared_ptr<Task> PollFirstTask(void); 83 84 /** 85 * Get count of tasks which were done. 86 * 87 * @return the count of tasks which were done. 88 * 89 */ 90 long GetTaskCounter(void); 91 92 std::shared_ptr<Thread> GetThread(void); 93 94 /** 95 * join thread 96 * 97 */ 98 void Join(); 99 100 protected: 101 std::shared_ptr<Thread> thread_; 102 std::atomic_long task_counter_; 103 104 private: 105 std::shared_ptr<Task> first_task_; 106 std::shared_ptr<Delegate> delegate_; 107 std::shared_ptr<ThreadFactory> factory_; 108 }; 109 110 } // namespace AppExecFwk 111 } // namespace OHOS 112 #endif 113