fork(2) download
  1. #include <future>
  2. #include <memory>
  3. #include <iostream>
  4.  
  5. class IWidget {
  6. public:
  7. virtual ~IWidget(){}
  8. virtual std::future<double> calculateSomethingAsync() const = 0;
  9. };
  10.  
  11. class Widget : public std::enable_shared_from_this<Widget>, public IWidget {
  12. double data;
  13.  
  14. double calculateSomethingInternal() const;
  15. protected:
  16. Widget(double init) : data(init) {} // protected, use create
  17. public:
  18. std::future<double> calculateSomethingAsync() const override;
  19.  
  20. static std::shared_ptr<IWidget> create(double init);
  21. };
  22.  
  23. std::shared_ptr<IWidget>
  24. Widget::create(double init) {
  25. return std::shared_ptr<IWidget>(new Widget(init));
  26. }
  27.  
  28. double
  29. Widget::calculateSomethingInternal() const {
  30. return (data + 5.0) / 2.0;
  31. }
  32.  
  33. std::future<double>
  34. Widget::calculateSomethingAsync() const {
  35. auto shared_this = shared_from_this();
  36. return std::async([shared_this]{ return shared_this->calculateSomethingInternal(); });
  37. }
  38.  
  39. int main() {
  40. std::future<double> result_task;
  41. {
  42. std::shared_ptr<IWidget> w = Widget::create(42.0);
  43. result_task = w->calculateSomethingAsync();
  44. } // w shared_ptr goes out-of-scope here.
  45. auto result = result_task.get();
  46. std::cout << result << "\n";
  47. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
23.5