• 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 #include "work_thread.h"
17 
18 namespace OHOS {
19 namespace AppExecFwk {
WorkerThread(const std::shared_ptr<Delegate> & delegate,const std::shared_ptr<Task> & firstTask,const std::shared_ptr<ThreadFactory> & factory)20 WorkerThread::WorkerThread(const std::shared_ptr<Delegate> &delegate, const std::shared_ptr<Task> &firstTask,
21     const std::shared_ptr<ThreadFactory> &factory)
22 {
23     task_counter_.store(0);
24 
25     first_task_ = firstTask;
26     delegate_ = delegate;
27     factory_ = factory;
28 }
29 
Join()30 void WorkerThread::Join()
31 {
32     if ((thread_) && (thread_->thread_) && thread_->thread_->joinable()) {
33         APP_LOGI("WorkerThread::Join joinable thread");
34         thread_->thread_->join();
35     }
36     APP_LOGI("WorkerThread::Join end");
37 }
38 
CreateThread()39 void WorkerThread::CreateThread()
40 {
41     thread_ = factory_->Create();
42     auto task = [&]() {
43         if (delegate_ != nullptr) {
44             auto ptr = shared_from_this();
45             delegate_->DoWorks(ptr);
46         };
47     };
48 
49     // start a thread to run task function.
50     thread_->thread_ = std::make_shared<std::thread>(task);
51     APP_LOGI("WorkerThread::CreateThread start thread. ");
52 }
53 
IncTaskCount()54 void WorkerThread::IncTaskCount()
55 {
56     task_counter_.fetch_add(1, std::memory_order_relaxed);
57 }
58 
GetThreadName()59 std::string WorkerThread::GetThreadName()
60 {
61     if (thread_ != nullptr) {
62         return thread_->thread_name_;
63     } else {
64         return std::string("");
65     }
66 }
67 
PollFirstTask(void)68 std::shared_ptr<Task> WorkerThread::PollFirstTask(void)
69 {
70     std::shared_ptr<Task> ret(nullptr);
71     if (first_task_ != nullptr) {
72         ret.swap(first_task_);
73     }
74     return ret;
75 }
76 
GetTaskCounter(void)77 long WorkerThread::GetTaskCounter(void)
78 {
79     long value = task_counter_;
80     return value;
81 }
82 
GetThread(void)83 std::shared_ptr<Thread> WorkerThread::GetThread(void)
84 {
85     return thread_;
86 }
87 
88 }  // namespace AppExecFwk
89 }  // namespace OHOS
90