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 
16 #ifndef FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_PROMISE_H
17 #define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_PROMISE_H
18 
19 #include <atomic>
20 #include <future>
21 
22 #include "app_log_wrapper.h"
23 
24 namespace OHOS {
25 namespace AppExecFwk {
26 class BundlePromise {
27 public:
28     BundlePromise() = default;
29     ~BundlePromise() = default;
30     /**
31      * @brief Notify all tasks has executed finished.
32      * @return
33      */
NotifyAllTasksExecuteFinished()34     void NotifyAllTasksExecuteFinished()
35     {
36         std::lock_guard<std::mutex> lock(notifyTaskMutex_);
37         if (hasNotified_) {
38             APP_LOGE("promise has executed and abort when NotifyAllTasksExecuteFinished");
39             return;
40         }
41 
42         APP_LOGD("Notify all tasks has executed finished");
43         hasNotified_ = true;
44         promise_.set_value();
45     }
46     /**
47      * @brief Wait for all tasks execute.
48      * @return
49      */
WaitForAllTasksExecute()50     void WaitForAllTasksExecute()
51     {
52         std::lock_guard<std::mutex> lock(waitTaskMutex_);
53         if (hasWaited_) {
54             APP_LOGE("promise has executed and abort when WaitForAllTasksExecute");
55             return;
56         }
57 
58         APP_LOGD("Wait for all tasks execute");
59         hasWaited_ = true;
60         future_.get();
61     }
62 private:
63     std::atomic_bool hasNotified_ = false;
64     std::atomic_bool hasWaited_ = false;
65     std::promise<void> promise_;
66     std::future<void> future_ = promise_.get_future();
67     std::mutex waitTaskMutex_;
68     std::mutex notifyTaskMutex_;
69 };
70 }  // namespace AppExecFwk
71 }  // namespace OHOS
72 #endif  // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_PROMISE_H
73