#include #include #include #include class shared_state { public: void set_value(int val) { std::unique_lock l(mtx); data = val; has_value = true; cond.notify_one(); } int get_value() { std::unique_lock l(mtx); if (!has_value) { cond.wait(l); } return data; } private: int data = 0; bool has_value = false; std::mutex mtx; std::condition_variable cond; }; class future { public: future(std::shared_ptr s) : state(s) { } int get() { return state->get_value(); } private: std::shared_ptr state; }; class promise { public: promise() : state(std::make_shared()) { } future get_future() { return future(state); } void set_value(int val) { state->set_value(val); } private: std::shared_ptr state; }; future async(int func()) { promise p; future f = p.get_future(); std::thread t ( [=]() mutable { int result = func(); p.set_value(result); }); t.detach(); return f; } int universal_answer() { return 42; } int main() { future f = async(&universal_answer); // do other things std::cout << "Universal answer: " << f.get() << "\n"; return 0; }