1 /*
2 * Copyright (c) 2023 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 "base_thread.h"
16 #include <unistd.h>
17 #include "intell_voice_log.h"
18
19 #define LOG_TAG "BaseThread"
20
21 using namespace std;
22
23 namespace OHOS {
24 namespace IntellVoiceUtils {
BaseThread()25 BaseThread::BaseThread() : tid_(0), isRuning_(false)
26 {
27 }
28
~BaseThread()29 BaseThread::~BaseThread()
30 {
31 if (isRuning_) {
32 pthread_detach(tid_);
33 }
34 }
35
RunInThread(void * arg)36 void *BaseThread::RunInThread(void *arg)
37 {
38 BaseThread *pt = static_cast<BaseThread *>(arg);
39 pt->Run();
40
41 return nullptr;
42 }
43
Start()44 void BaseThread::Start()
45 {
46 std::lock_guard<std::mutex> lock(mutex_);
47
48 int ret = pthread_create(&tid_, nullptr, BaseThread::RunInThread, this);
49 if (ret != 0) {
50 INTELL_VOICE_LOG_ERROR("create thread failed");
51 return;
52 }
53
54 isRuning_ = true;
55 }
56
Join()57 void BaseThread::Join()
58 {
59 std::lock_guard<std::mutex> lock(mutex_);
60
61 if (!isRuning_) {
62 return;
63 }
64
65 pthread_join(tid_, nullptr);
66 isRuning_ = false;
67 }
68
IsRuning() const69 bool BaseThread::IsRuning() const
70 {
71 return isRuning_;
72 }
73
Gettid() const74 pid_t BaseThread::Gettid() const
75 {
76 return tid_;
77 }
78 }
79 }
80