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