You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.7 KiB

  1. #pragma once
  2. #include "cancellation_token.h"
  3. namespace cppcore
  4. {
  5. /* cancellation_exception */
  6. const char* cancellation_exception
  7. ::what() const throw()
  8. { return "task was canceled!"; }
  9. /* data_cancellation_exception */
  10. template<typename T>
  11. data_cancellation_exception<T>::data_cancellation_exception(const T& d)
  12. : data(d)
  13. { }
  14. /* data_cancellation_exception<void> */
  15. template<>
  16. struct data_cancellation_exception<void>
  17. : public cancellation_exception
  18. { };
  19. /* cancellation_token */
  20. cancellation_token
  21. ::cancellation_token()
  22. : _is_cancellation_requested(false)
  23. { }
  24. bool cancellation_token
  25. ::is_cancellation_requested() const
  26. { return _is_cancellation_requested; }
  27. void cancellation_token
  28. ::cancel()
  29. { _is_cancellation_requested = true; }
  30. /* cancellation_source */
  31. template<typename T>
  32. void cancellation_source<T>
  33. ::throw_if_cancellation_requested() const
  34. {
  35. if (is_cancellation_requested())
  36. throw data_cancellation_exception<T>(_value);
  37. }
  38. template<typename T>
  39. void cancellation_source<T>
  40. ::cancel(const T& value)
  41. {
  42. cancellation_token::cancel();
  43. _value = value;
  44. }
  45. /* cancellation_source<void> */
  46. template<>
  47. struct cancellation_source<void>
  48. : public cancellation_token
  49. {
  50. public:
  51. inline void throw_if_cancellation_requested() const
  52. {
  53. if (is_cancellation_requested())
  54. throw cancellation_exception();
  55. }
  56. inline void cancel()
  57. { cancellation_token::cancel(); }
  58. };
  59. }