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 "thread_wrapper.h" 16#include "intell_voice_log.h" 17 18#define LOG_TAG "ThreadWrapper" 19 20namespace OHOS { 21namespace IntellVoiceUtils { 22ThreadWrapper::~ThreadWrapper() 23{ 24 Join(); 25} 26 27bool ThreadWrapper::Start(const std::string &name, TaskQoS qos) 28{ 29 std::unique_lock uniqueLock(mutex_); 30 if (thread_ != nullptr) { 31 INTELL_VOICE_LOG_WARN("thread is already started, name:%{public}s", name.c_str()); 32 return true; 33 } 34 35#ifdef USE_FFRT 36 INTELL_VOICE_LOG_INFO("use ffrt"); 37 thread_ = std::make_unique<ffrt::thread>(name.c_str(), Convert2FfrtQos(qos), &ThreadWrapper::RunInThread, this); 38#else 39 INTELL_VOICE_LOG_INFO("do not use ffrt"); 40 thread_ = std::make_unique<std::thread>(&ThreadWrapper::RunInThread, this); 41#endif 42 43 if (thread_ == nullptr) { 44 INTELL_VOICE_LOG_ERROR("failed to create thread"); 45 return false; 46 } 47 48#ifndef USE_FFRT 49 pthread_setname_np(thread_->native_handle(), name.c_str()); 50#endif 51 return true; 52} 53 54void ThreadWrapper::Join() 55{ 56 std::unique_lock uniqueLock(mutex_); 57 if (thread_ == nullptr) { 58 return; 59 } 60 if (thread_->joinable()) { 61 uniqueLock.unlock(); 62 thread_->join(); 63 uniqueLock.lock(); 64 } 65 thread_.reset(); 66} 67 68void ThreadWrapper::RunInThread() 69{ 70 Run(); 71} 72 73#ifdef USE_FFRT 74ffrt::qos ThreadWrapper::Convert2FfrtQos(TaskQoS taskqos) 75{ 76 switch (taskqos) { 77 case TaskQoS::INHERENT: 78 return ffrt::qos_inherit; 79 case TaskQoS::BACKGROUND: 80 return ffrt::qos_background; 81 case TaskQoS::UTILITY: 82 return ffrt::qos_utility; 83 case TaskQoS::DEFAULT: 84 return ffrt::qos_default; 85 case TaskQoS::USER_INITIATED: 86 return ffrt::qos_user_initiated; 87 case TaskQoS::DEADLINE_REQUEST: 88 return ffrt::qos_deadline_request; 89 case TaskQoS::USER_INTERACTIVE: 90 return ffrt::qos_user_interactive; 91 default: 92 break; 93 } 94 95 return ffrt::qos_inherit; 96} 97#endif 98} 99}