ADTF
looper.h
Go to the documentation of this file.
1 
7 #ifndef _A_UTILS_LOOPER_HEADER_
8 #define _A_UTILS_LOOPER_HEADER_
9 
10 #include <mutex>
11 #include <future>
12 
13 namespace A_UTILS_NS
14 {
20 class cLooper
21 {
22  public:
26  enum class tLoopState
27  {
29  Destroyed,
31  Suspended,
33  Running
34  };
35 
36  private:
37  struct ImplBase;
38  typedef std::shared_ptr<ImplBase> shared_base_type;
39 
40  struct ImplBase
41  {
42  tLoopState m_eLoopState;
43  tBool m_bStateAcked = tTrue;
44  std::promise<void> m_oLoopStateAck;
45  std::mutex m_oStateMutex;
46  std::condition_variable m_oWakeup;
47 
48  inline virtual ~ImplBase() {}
49  virtual void Run() = 0;
50  };
51 
52  template<typename Callable>
53  struct Impl : public ImplBase
54  {
55  Callable pFunc;
56 
57  Impl(Callable&& pFunc) : pFunc(std::forward<Callable>(pFunc))
58  {
59  }
60 
61  void Run()
62  {
63  pFunc();
64  }
65  };
66 
67  template<typename Callable>
68  std::shared_ptr<Impl<Callable>> MakeCallable(Callable&& pFunc)
69  {
70  return std::make_shared<Impl<Callable>>(std::forward<Callable>(pFunc));
71  }
72 
73  shared_base_type m_pCallable;
74 
75  public:
78  cLooper(cLooper&&);
79 
80  cLooper(const cLooper&) = delete;
81 
82  template<typename ...Args>
83  cLooper(Args&&... args): cLooper(tLoopState::Running, std::forward<Args>(args)...)
84  {
85  }
86 
87  template<typename Callable, typename ...Args>
88  cLooper(tLoopState eState, Callable&& pFunc, Args&&... args)
89  {
90  m_pCallable = MakeCallable(std::bind(std::forward<Callable>(pFunc),
91  std::forward<Args>(args)...));
92  ResetLoop(eState);
93  }
94 
95  virtual ~cLooper();
96 
97  cLooper& operator=(cLooper&& oOther);
98 
99  tLoopState GetState();
100  tResult SetState(tLoopState eState, tBool bWaitForAck = tTrue);
101  tVoid ResetLoop(tLoopState eInitialState = tLoopState::Running);
102 
103  tVoid Swap(cLooper& oOther);
104 
105  std::function<void()> GetCallable()
106  {
107  return std::bind(CallableHelper, m_pCallable);
108  }
109 
110  private:
111  static tVoid CallableHelper(shared_base_type pImpl);
112 };
113 
114 }
115 
116 #endif
void tVoid
The tVoid is always the definition for the void (non-type).
bool tBool
The tBool defines the type for the Values tTrue and tFalse (platform and compiler dependent).
The looper helper class is a managed endless loop, which can be suspended.
Definition: looper.h:21
tLoopState
Loop state.
Definition: looper.h:27
@ Suspended
loop is suspended
@ Destroyed
loop is finished or only constructed
#define tTrue
Value for tBool.
Definition: constants.h:62
ADTF A_UTIL Namespace - Within adtf this is used as adtf::util or adtf_util.
Definition: d_ptr.h:11