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_EXT_TASK_QUEUE_H
17 #define META_EXT_TASK_QUEUE_H
18
19 #include <base/containers/type_traits.h>
20
21 #include <meta/ext/object_fwd.h>
22 #include <meta/interface/interface_helpers.h>
23 #include <meta/interface/intf_promise.h>
24 #include <meta/interface/intf_task_queue_extend.h>
25
META_BEGIN_NAMESPACE()26 META_BEGIN_NAMESPACE()
27
28 /// Task implementation for futures
29 class PromisedQueueTask : public IntroduceInterfaces<ITaskQueueTask, ITaskScheduleInfo> {
30 public:
31 PromisedQueueTask(ITaskQueueWaitableTask::Ptr task, IPromise::Ptr p)
32 : task_(BASE_NS::move(task)), promise_(BASE_NS::move(p))
33 {}
34
35 bool Invoke() override
36 {
37 auto res = task_->Invoke();
38 // make sure the task is destroyed before future wait returns,
39 // so that any captured objects are also destroyed.
40 task_.reset();
41 promise_->Set(BASE_NS::move(res));
42 return false;
43 }
44
45 void SetQueueAndToken(const ITaskQueue::Ptr& q, ITaskQueue::Token t) override
46 {
47 promise_->SetQueueInfo(q, t);
48 }
49
50 [[nodiscard]] IFuture::Ptr GetFuture()
51 {
52 return promise_->GetFuture();
53 }
54
55 IPromise::Ptr GetPromise()
56 {
57 return promise_;
58 }
59
60 private:
61 ITaskQueueWaitableTask::Ptr task_;
62 IPromise::Ptr promise_;
63 };
64
65 META_END_NAMESPACE()
66
67 #endif
68