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 IM_RENDER_TASK_H
17 #define IM_RENDER_TASK_H
18 
19 #include "render_task_itf.h"
20 
21 #include <memory>
22 #include <map>
23 #include <iostream>
24 #include <functional>
25 #include <future>
26 
27 template <typename RETURNTYPE = void, typename... ARGSTYPE>
28 class RenderTask : public RenderTaskItf<RETURNTYPE, ARGSTYPE...> {
29 public:
30     RenderTask(std::function<RETURNTYPE(ARGSTYPE...)> run, uint64_t tag = 0, uint64_t id = 0)
31         : m_runFunc(run), m_barrier(), m_barrierFuture(m_barrier.get_future())
32     {
33         RenderTaskItf<RETURNTYPE, ARGSTYPE...>::SetTag(tag);
34         RenderTaskItf<RETURNTYPE, ARGSTYPE...>::SetId(id);
35         RenderTaskItf<RETURNTYPE, ARGSTYPE...>::SetSequenceId(0);
36     }
37     ~RenderTask() = default;
38 
Run(ARGSTYPE...args)39     void Run(ARGSTYPE... args) override
40     {
41         RunImpl<decltype(this), RETURNTYPE, ARGSTYPE...> impl(this);
42         impl(args...);
43     };
44 
Wait()45     void Wait() override
46     {
47         m_barrierFuture.wait();
48     };
49 
GetReturn()50     RETURNTYPE GetReturn() override
51     {
52         return m_barrierFuture.get();
53     };
54 
GetFuture()55     std::shared_future<RETURNTYPE> GetFuture() override
56     {
57         return m_barrierFuture;
58     };
59 
60 private:
61     template <typename THISPTYTPE, typename RUNRETURNTYPE, typename... RUNARGSTYPE> class RunImpl {
62     public:
RunImpl(THISPTYTPE p)63         explicit RunImpl(THISPTYTPE p)
64         {
65             m_p = p;
66         }
operator()67         void operator () (RUNARGSTYPE... args)
68         {
69             m_p->m_barrier.set_value(m_p->m_runFunc(args...));
70         }
71         THISPTYTPE m_p;
72     };
73 
74     template <typename THISPTYTPE, typename... RUNARGSTYPE> struct RunImpl<THISPTYTPE, void, RUNARGSTYPE...> {
75         explicit RunImpl(THISPTYTPE p)
76         {
77             m_p = p;
78         }
79         void operator () (RUNARGSTYPE... args)
80         {
81             m_p->m_runFunc(args...);
82             m_p->m_barrier.set_value();
83         }
84         THISPTYTPE m_p;
85     };
86 
87     std::function<RETURNTYPE(ARGSTYPE...)> m_runFunc;
88     std::promise<RETURNTYPE> m_barrier;
89     std::shared_future<RETURNTYPE> m_barrierFuture;
90 };
91 #endif