1 /* 2 * Copyright (c) 2022 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_handler_impl.h" 16 17 #include <cstdint> 18 #include <functional> 19 #include <future> 20 #include <memory> 21 22 #include "nocopyable.h" 23 24 #include "iam_logger.h" 25 #include "iam_ptr.h" 26 #include "thread_handler_manager.h" 27 #include "xcollie_helper.h" 28 29 #define LOG_TAG "USER_AUTH_SA" 30 31 namespace OHOS { 32 namespace UserIam { 33 namespace UserAuth { 34 using namespace OHOS; 35 using namespace OHOS::UserIam::Common; 36 constexpr uint32_t TASK_BLOCK_MONITOR_TIMEOUT = 20; 37 ThreadHandlerImpl(std::string name,bool canSuspend)38ThreadHandlerImpl::ThreadHandlerImpl(std::string name, bool canSuspend) : pool_(name), canSuspend_(canSuspend) 39 { 40 pool_.Start(1); 41 } 42 ~ThreadHandlerImpl()43ThreadHandlerImpl::~ThreadHandlerImpl() 44 { 45 pool_.Stop(); 46 } 47 PostTask(const Task & task)48void ThreadHandlerImpl::PostTask(const Task &task) 49 { 50 std::lock_guard<std::recursive_mutex> lock(mutex_); 51 if (isSuspended_) { 52 IAM_LOGE("is suspended"); 53 return; 54 } 55 pool_.AddTask(task); 56 57 auto taskBlockMonitor = MakeShared<XCollieHelper>("taskBlockMonitor", TASK_BLOCK_MONITOR_TIMEOUT); 58 if (taskBlockMonitor == nullptr) { 59 IAM_LOGE("taskBlockMonitor is nullptr"); 60 return; 61 } 62 pool_.AddTask([taskBlockMonitor] { 63 (void)taskBlockMonitor; 64 }); 65 } 66 EnsureTask(const Task & task)67void ThreadHandlerImpl::EnsureTask(const Task &task) 68 { 69 std::promise<void> ensure; 70 auto callback = [&ensure]() { 71 ensure.set_value(); 72 return; 73 }; 74 PostTask(task); 75 PostTask(callback); 76 ensure.get_future().get(); 77 } 78 Suspend()79void ThreadHandlerImpl::Suspend() 80 { 81 std::lock_guard<std::recursive_mutex> lock(mutex_); 82 if (!canSuspend_) { 83 IAM_LOGE("can not suspend"); 84 return; 85 } 86 isSuspended_ = true; 87 } 88 GetSingleThreadInstance()89std::shared_ptr<ThreadHandler> ThreadHandler::GetSingleThreadInstance() 90 { 91 return ThreadHandlerManager::GetInstance().GetThreadHandler(SINGLETON_THREAD_NAME); 92 } 93 } // namespace UserAuth 94 } // namespace UserIam 95 } // namespace OHOS