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 "thread_handler.h"
16 
17 #include <cstdint>
18 #include <functional>
19 #include <future>
20 #include <memory>
21 
22 #include "nocopyable.h"
23 #include "singleton.h"
24 #include "thread_pool.h"
25 
26 #include "iam_logger.h"
27 
28 #define LOG_TAG "FACE_AUTH_SA"
29 
30 namespace OHOS {
31 namespace UserIam {
32 namespace FaceAuth {
33 using namespace OHOS;
34 
35 class ThreadHandlerImpl : public ThreadHandler, public DelayedSingleton<ThreadHandlerImpl> {
36 public:
37     ThreadHandlerImpl();
38     ~ThreadHandlerImpl() override;
39     void PostTask(const Task &task) override;
40     void EnsureTask(const Task &task) override;
41 
42 private:
43     OHOS::ThreadPool pool_;
44 };
45 
ThreadHandlerImpl()46 ThreadHandlerImpl::ThreadHandlerImpl()
47 {
48     pool_.Start(1);
49 }
50 
~ThreadHandlerImpl()51 ThreadHandlerImpl::~ThreadHandlerImpl()
52 {
53     pool_.Stop();
54 }
55 
PostTask(const Task & task)56 void ThreadHandlerImpl::PostTask(const Task &task)
57 {
58     pool_.AddTask(task);
59 }
60 
EnsureTask(const Task & task)61 void ThreadHandlerImpl::EnsureTask(const Task &task)
62 {
63     std::promise<void> ensure;
64     auto callback = [&ensure]() {
65         ensure.set_value();
66         return;
67     };
68     pool_.AddTask(task);
69     pool_.AddTask(callback);
70     ensure.get_future().get();
71 }
72 
GetSingleThreadInstance()73 std::shared_ptr<ThreadHandler> ThreadHandler::GetSingleThreadInstance()
74 {
75     return ThreadHandlerImpl::GetInstance();
76 }
77 } // namespace FaceAuth
78 } // namespace UserIam
79 } // namespace OHOS