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_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_PIPELINE_CONTEXT_HOLDER_H
17 #define FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_PIPELINE_CONTEXT_HOLDER_H
18 
19 #include <future>
20 
21 #include "base/thread/task_executor.h"
22 #include "core/pipeline/pipeline_base.h"
23 
24 namespace OHOS::Ace::Framework {
25 
26 class PipelineContextHolder {
27 public:
~PipelineContextHolder()28     ~PipelineContextHolder()
29     {
30         if (pipelineContext_) {
31             auto taskExecutor = pipelineContext_->GetTaskExecutor();
32             // To guarantee the pipelineContext_ destruct in platform thread
33             auto context = AceType::RawPtr(pipelineContext_);
34             context->IncRefCount();
35             pipelineContext_.Reset();
36             taskExecutor->PostTask(
37                 [context] { context->DecRefCount(); }, TaskExecutor::TaskType::PLATFORM, "ArkUIDecRefCount");
38         }
39     }
40 
Attach(const RefPtr<PipelineBase> & context)41     void Attach(const RefPtr<PipelineBase>& context)
42     {
43         if (attached_) {
44             return;
45         }
46         if (!context) {
47             return;
48         }
49 
50         attached_ = true;
51         promise_.set_value(context);
52     }
53 
Get()54     const RefPtr<PipelineBase>& Get()
55     {
56         if (!pipelineContext_) {
57             pipelineContext_ = future_.get();
58             ACE_DCHECK(pipelineContext_);
59         }
60         return pipelineContext_;
61     }
62 
63 private:
64     bool attached_ = false;
65     std::promise<RefPtr<PipelineBase>> promise_;
66     std::future<RefPtr<PipelineBase>> future_ = promise_.get_future();
67     RefPtr<PipelineBase> pipelineContext_;
68 };
69 
70 }
71 #endif // FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_PIPELINE_CONTEXT_HOLDER_H