Scarab  v3.8.0
Project 8 C++ Utility Library
cancelable.hh
Go to the documentation of this file.
1 /*
2  * cancelable.hh
3  *
4  * Created on: Jan 24, 2016
5  * Author: nsoblath
6  *
7  * Base class for thread-safe asynchronous cancellation
8  */
9 
10 #ifndef SCARAB_CANCELABLE_HH_
11 #define SCARAB_CANCELABLE_HH_
12 
13 #include "macros.hh"
14 #include "scarab_api.hh"
15 
16 #include <atomic>
17 #include <memory>
18 
19 namespace scarab
20 {
52  {
53  public:
54  cancelable();
55  cancelable( const cancelable& a_orig );
56  cancelable( cancelable&& a_orig );
57  virtual ~cancelable();
58 
59  cancelable& operator=( const cancelable& a_orig );
60  cancelable& operator=( cancelable&& a_orig );
61 
63  void cancel( int a_code = RETURN_SUCCESS );
64 
66  void reset_cancel();
67 
69  bool is_canceled() const;
70 
71  private:
72  virtual void do_cancellation( int a_code );
73  virtual void do_reset_cancellation();
74 
75  protected:
76  std::atomic< bool > f_canceled;
77  };
78 
104  {
105  cancelable_wrapper( cancelable& a_cancelable );
106  virtual ~cancelable_wrapper();
107  virtual void do_cancellation( int a_code );
109  };
110 
112  SCARAB_API std::shared_ptr< cancelable_wrapper > wrap_cancelable( cancelable& a_cancelable );
113 
114 
115  inline void cancelable::cancel( int a_code )
116  {
117  if( f_canceled.load() ) return;
118  f_canceled.store( true );
119  this->do_cancellation( a_code );
120  }
121 
123  {
124  if( ! f_canceled.load() ) return;
125  f_canceled.store( false );
126  this->do_reset_cancellation();
127  }
128 
129  inline bool cancelable::is_canceled() const
130  {
131  return f_canceled.load();
132  }
133 
134 
135  inline void cancelable_wrapper::do_cancellation( int a_code )
136  {
137  f_wrapped->cancel( a_code );
138  }
139 
140 } /* namespace scarab */
141 
142 #endif /* SCARAB_CANCELABLE_HH_ */
#define RETURN_SUCCESS
Definition: macros.hh:12
#define SCARAB_API
Definition: scarab_api.hh:24
std::shared_ptr< cancelable_wrapper > wrap_cancelable(cancelable &a_cancelable)
Convenience function to create a cancelable_wrapper.
Definition: cancelable.cc:77
bool is_canceled() const
check canceled state
Definition: cancelable.hh:129
virtual void do_cancellation(int a_code)
Definition: cancelable.hh:135
void reset_cancel()
reset to non-canceled state
Definition: cancelable.hh:122
std::atomic< bool > f_canceled
Definition: cancelable.hh:76
void cancel(int a_code=0)
asynchronous cancel function
Definition: cancelable.hh:115
Base class for a cancelable object (i.e. an object that can be canceled by scarab::signal_handler or ...
Definition: cancelable.hh:51
Lightweight wrapper for a cancelable object only temporarily added to signal_handler.
Definition: cancelable.hh:103