Virtual Testbed
Ship dynamics simulator for extreme conditions
Task.hh
1 #ifndef VTESTBED_GUI_TASK_HH
2 #define VTESTBED_GUI_TASK_HH
3 
4 #include <atomic>
5 #include <exception>
6 #include <thread>
7 
8 namespace vtb {
9 
10  namespace gui {
11 
12  class Task {
13 
14  private:
15  enum class State {
16  Initial,
17  Running,
18  Finished
19  };
20 
21  private:
22  std::thread _thread;
23  std::exception_ptr _exception;
24  std::atomic<State> _state{State::Initial};
25 
26  public:
27 
28  Task() = default;
29 
30  template <class Function>
31  inline void
32  run(Function function) {
33  this->_state = State::Running;
34  this->_thread = std::thread{
35  [function,this] () {
36  try {
37  function();
38  this->_exception = nullptr;
39  } catch (...) {
40  this->_exception = std::current_exception();
41  }
42  this->_state = State::Finished;
43  }
44  };
45  }
46 
47  inline bool
48  initial() const {
49  return this->_state == State::Initial;
50  }
51 
52  inline bool
53  finished() const {
54  return this->_state == State::Finished;
55  }
56 
57  inline bool
58  running() const {
59  return this->_state == State::Running;
60  }
61 
62  inline void
63  wait() {
64  if (this->_thread.joinable()) {
65  this->_thread.join();
66  }
67  auto ptr = this->_exception;
68  clear();
69  if (ptr) {
70  std::rethrow_exception(ptr);
71  }
72  }
73 
74  inline void
75  clear() {
76  this->_exception = nullptr;
77  this->_state = State::Initial;
78  }
79 
80  };
81 
82  }
83 
84 }
85 
86 #endif // vim:filetype=cpp
Main namespace.
Definition: convert.hh:9