• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 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 #include "task_executor.h"
16 #include <sys/prctl.h>
17 #include "intell_voice_log.h"
18 
19 #define LOG_TAG "TaskExecutor"
20 
21 namespace OHOS {
22 namespace IntellVoiceUtils {
TaskExecutor(const std::string & threadName,uint32_t capacity)23 TaskExecutor::TaskExecutor(const std::string &threadName, uint32_t capacity) : threadName_(threadName)
24 {
25     INTELL_VOICE_LOG_INFO("constructor, thread name:%{public}s, capacity:%{public}u", threadName_.c_str(), capacity);
26     Init(capacity);
27 }
28 
~TaskExecutor()29 TaskExecutor::~TaskExecutor()
30 {
31     StopThread();
32     INTELL_VOICE_LOG_INFO("destructor, thread name:%{public}s", threadName_.c_str());
33 }
34 
StartThread()35 void TaskExecutor::StartThread()
36 {
37     INTELL_VOICE_LOG_INFO("enter");
38     std::lock_guard<std::mutex> lock(mutex_);
39     int ret = pthread_create(&tid_, nullptr, TaskExecutor::ExecuteInThread, this);
40     if (ret != 0) {
41         INTELL_VOICE_LOG_ERROR("create thread failed");
42         return;
43     }
44 
45     isRuning_ = true;
46 }
47 
StopThread()48 void TaskExecutor::StopThread()
49 {
50     INTELL_VOICE_LOG_INFO("enter");
51     Uninit();
52     std::lock_guard<std::mutex> lock(mutex_);
53     if (!isRuning_) {
54         INTELL_VOICE_LOG_INFO("not running");
55         return;
56     }
57 
58     pthread_join(tid_, nullptr);
59     isRuning_ = false;
60     INTELL_VOICE_LOG_INFO("exit");
61 }
62 
ExecuteInThread(void * arg)63 void *TaskExecutor::ExecuteInThread(void *arg)
64 {
65     TaskExecutor *executor = static_cast<TaskExecutor *>(arg);
66     if (executor == nullptr) {
67         INTELL_VOICE_LOG_ERROR("executor is nullptr");
68         return nullptr;
69     }
70     prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(executor->threadName_.c_str()), 0, 0, 0);
71     do {
72         std::function<void()> task;
73         if (!executor->Pop(task)) {
74             INTELL_VOICE_LOG_INFO("no task needed to execute");
75             break;
76         }
77         task();
78     } while (1);
79     return nullptr;
80 }
81 }
82 }