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
21namespace OHOS {
22namespace IntellVoiceUtils {
23TaskExecutor::TaskExecutor(const std::string &threadName, uint32_t capacity) : threadName_(threadName)
24{
25    Init(capacity);
26}
27
28TaskExecutor::~TaskExecutor()
29{
30    StopThread();
31}
32
33void TaskExecutor::StartThread()
34{
35    std::lock_guard<std::mutex> lock(mutex_);
36    int ret = pthread_create(&tid_, nullptr, TaskExecutor::ExecuteInThread, this);
37    if (ret != 0) {
38        INTELL_VOICE_LOG_ERROR("create thread failed");
39        return;
40    }
41
42    isRuning_ = true;
43}
44
45void TaskExecutor::StopThread()
46{
47    Uninit();
48    std::lock_guard<std::mutex> lock(mutex_);
49    if (!isRuning_) {
50        return;
51    }
52
53    pthread_join(tid_, nullptr);
54    isRuning_ = false;
55}
56
57void *TaskExecutor::ExecuteInThread(void *arg)
58{
59    TaskExecutor *executor = static_cast<TaskExecutor *>(arg);
60    if (executor == nullptr) {
61        INTELL_VOICE_LOG_ERROR("executor is nullptr");
62        return nullptr;
63    }
64    prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(executor->threadName_.c_str()), 0, 0, 0);
65    do {
66        std::function<void()> task;
67        if (!executor->Pop(task)) {
68            INTELL_VOICE_LOG_INFO("no task needed to execute");
69            break;
70        }
71        task();
72    } while (1);
73    return nullptr;
74}
75}
76}