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([context] { context->DecRefCount(); }, TaskExecutor::TaskType::PLATFORM); 37 } 38 } 39 Attach(const RefPtr<PipelineBase> & context)40 void Attach(const RefPtr<PipelineBase>& context) 41 { 42 if (attached_) { 43 return; 44 } 45 if (!context) { 46 return; 47 } 48 49 attached_ = true; 50 promise_.set_value(context); 51 } 52 Get()53 const RefPtr<PipelineBase>& Get() 54 { 55 if (!pipelineContext_) { 56 pipelineContext_ = future_.get(); 57 ACE_DCHECK(pipelineContext_); 58 } 59 return pipelineContext_; 60 } 61 62 private: 63 bool attached_ = false; 64 std::promise<RefPtr<PipelineBase>> promise_; 65 std::future<RefPtr<PipelineBase>> future_ = promise_.get_future(); 66 RefPtr<PipelineBase> pipelineContext_; 67 }; 68 69 } 70 #endif // FOUNDATION_ACE_FRAMEWORKS_BRIDGE_COMMON_UTILS_PIPELINE_CONTEXT_HOLDER_H