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 16 #ifndef META_API_TASK_H 17 #define META_API_TASK_H 18 19 #include <base/containers/type_traits.h> 20 21 #include <meta/interface/detail/any.h> 22 #include <meta/interface/interface_helpers.h> 23 #include <meta/interface/intf_task_queue.h> 24 META_BEGIN_NAMESPACE()25META_BEGIN_NAMESPACE() 26 27 template<typename Func> 28 IAny::Ptr InvokeWaitableTaskFunction(Func&& func) 29 { 30 using Result = BASE_NS::remove_reference_t<decltype(func())>; 31 if constexpr (!BASE_NS::is_same_v<Result, void>) { 32 return IAny::Ptr(ConstructAny(func())); 33 } else { 34 func(); 35 return nullptr; 36 } 37 } 38 39 /** 40 * @brief Implementation of waitable task for task queues (see ITaskQueue::AddWaitableTask) 41 */ 42 template<typename Func> 43 class QueueWaitableTask : public IntroduceInterfaces<ITaskQueueWaitableTask> { 44 public: QueueWaitableTask(Func func)45 QueueWaitableTask(Func func) : func_(BASE_NS::move(func)) {} 46 Invoke()47 IAny::Ptr Invoke() override 48 { 49 return InvokeWaitableTaskFunction(func_); 50 } 51 52 private: 53 Func func_; 54 }; 55 56 /** 57 * @brief Create waitable task from callable entity (e.g. lambda). 58 */ 59 template<typename Func> CreateWaitableTask(Func func)60ITaskQueueWaitableTask::Ptr CreateWaitableTask(Func func) 61 { 62 return ITaskQueueWaitableTask::Ptr(new QueueWaitableTask(BASE_NS::move(func))); 63 } 64 65 META_END_NAMESPACE() 66 67 #endif 68