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 "account_timeout_task.h"
16 #include <thread>
17 
18 namespace OHOS {
19 namespace AccountSA {
RunTask(std::string taskName,std::function<void ()> callback,int32_t timeout)20 bool AccountTimeoutTask::RunTask(std::string taskName, std::function<void()> callback, int32_t timeout)
21 {
22     auto task = [callback, weakPtr = weak_from_this()] {
23         callback();
24         auto ptr = weakPtr.lock();
25         if (ptr) {
26             std::unique_lock<std::mutex> lock(ptr->mutex_);
27             ptr->isCalled_ = true;
28             ptr->cv_.notify_one();
29         }
30     };
31 
32     std::thread taskThread(task);
33     pthread_setname_np(taskThread.native_handle(), taskName.c_str());
34     taskThread.detach();
35 
36     std::unique_lock<std::mutex> lock(mutex_);
37     return cv_.wait_for(lock, std::chrono::seconds(timeout), [this] { return isCalled_; });
38 }
39 } // namespace AccountSA
40 } // namespace OHOS