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 #include "thread_handler_manager.h"
24 
25 #include "iam_logger.h"
26 
27 #define LOG_TAG "USER_AUTH_SA"
28 
29 namespace OHOS {
30 namespace UserIam {
31 namespace UserAuth {
32 using namespace OHOS;
ThreadHandlerImpl(std::string name,bool canSuspend)33 ThreadHandlerImpl::ThreadHandlerImpl(std::string name, bool canSuspend) : pool_(name), canSuspend_(canSuspend)
34 {
35     pool_.Start(1);
36 }
37 
~ThreadHandlerImpl()38 ThreadHandlerImpl::~ThreadHandlerImpl()
39 {
40     pool_.Stop();
41 }
42 
PostTask(const Task & task)43 void ThreadHandlerImpl::PostTask(const Task &task)
44 {
45     std::lock_guard<std::recursive_mutex> lock(mutex_);
46     if (isSuspended_) {
47         IAM_LOGE("is suspended");
48         return;
49     }
50     pool_.AddTask(task);
51 }
52 
EnsureTask(const Task & task)53 void ThreadHandlerImpl::EnsureTask(const Task &task)
54 {
55     std::promise<void> ensure;
56     auto callback = [&ensure]() {
57         ensure.set_value();
58         return;
59     };
60     PostTask(task);
61     PostTask(callback);
62     ensure.get_future().get();
63 }
64 
Suspend()65 void ThreadHandlerImpl::Suspend()
66 {
67     std::lock_guard<std::recursive_mutex> lock(mutex_);
68     if (!canSuspend_) {
69         IAM_LOGE("can not suspend");
70         return;
71     }
72     isSuspended_ = true;
73 }
74 
GetSingleThreadInstance()75 std::shared_ptr<ThreadHandler> ThreadHandler::GetSingleThreadInstance()
76 {
77     return ThreadHandlerManager::GetInstance().GetThreadHandler(SINGLETON_THREAD_NAME);
78 }
79 } // namespace UserAuth
80 } // namespace UserIam
81 } // namespace OHOS