Utilities
Utilities header only library
ConcurrentBinding.h
1 /*
2  Copyright (C) Skeletex Research, s.r.o. - All Rights Reserved
3  Unauthorized copying of this file, via any medium is strictly prohibited
4  Proprietary and confidential
5 */
6 #ifndef UTILS_CONCURRENT_BINDING_H
7 #define UTILS_CONCURRENT_BINDING_H
8 #include <future>
9 #include <functional>
10 #include "EventHandler.h"
11 
12 namespace utils
13 {
14 
22  template<typename T>
24  {
25  public:
27  void Run(const std::function<T(void)> &func)
28  {
29  result_ = std::async(
30  std::launch::async,
31  std::bind(&ConcurrentBinding::ParallelFunction, this, func)
32  );
33  }
34 
36  bool IsRunning() const
37  {
38  if (result_.valid())
39  {
40  using namespace std::chrono_literals;
41  const auto status = result_.wait_for(0ms);
42  return status != std::future_status::ready;
43  }
44  return false;
45  }
46 
48  void SetCallbackOnFinish(const std::function<void(T)> &func)
49  {
50  callback_on_finish_ = func;
51  }
52 
53  private:
54  std::function<void(T)> callback_on_finish_;
55  std::future<T> result_;
56 
57  T ParallelFunction(const std::function<T(void)> &func)
58  {
59  const auto result = func();
60  RegisterEvent("Finished");
61  return result;
62  }
63 
64  virtual void ProcessEvent(const Event *e) override
65  {
66  if (e->id == "Finished" && callback_on_finish_ && result_.valid())
67  {
68  callback_on_finish_(result_.get());
69  }
70  }
71  };
72 
73 }
74 #endif /* !UTILS_CONCURRENT_BINDING_H */
Default event. Inherit this structure to create custom event.
Definition: EventHandler.h:38
void RegisterEvent(Args... args)
Adds new event to the event queue.
Definition: EventHandler.h:47
Controller for binding asynchronous processes.
Definition: ConcurrentBinding.h:23
Contains common lambda functions.
Definition: Functional.h:12
void Run(const std::function< T(void)> &func)
Execute provided function asynchronously from a caller thread.
Definition: ConcurrentBinding.h:27
General namespace for utilities.
Definition: BulletConversions.h:9
bool IsRunning() const
Check if asynchronous function is still running.
Definition: ConcurrentBinding.h:36
Provides an interface for registering and processing events for inherited classes.
Definition: EventHandler.h:22
void SetCallbackOnFinish(const std::function< void(T)> &func)
Set callback which will be called via PollEvents after asynchronous function is finished.
Definition: ConcurrentBinding.h:48