#ifndef FUTURE_HPP #define FUTURE_HPP #include #include #include #include namespace detail { template class return_value { public: class exception_holder_base { public: virtual ~exception_holder_base() { } virtual void raise() const = 0; }; template class exception_holder : public exception_holder_base { public: exception_holder(E e) : e_(e) { } virtual void raise() const { throw e_; } private: E e_; }; T get() const { boost::mutex::scoped_lock lock(mutex_); while (!value_.get() && !exception_.get()) condition_.wait(lock); if (exception_.get()) exception_->raise(); return *value_; } void set(T t) { boost::mutex::scoped_lock lock(mutex_); if (value_.get() == 0 && exception_.get() == 0) { value_.reset(new T(t)); condition_.notify_all(); } } template void fail(E e) { boost::mutex::scoped_lock lock(mutex_); if (value_.get() == 0 && exception_.get() == 0) { exception_.reset(new exception_holder(e)); condition_.notify_all(); } } private: mutable boost::mutex mutex_; mutable boost::condition condition_; std::auto_ptr value_; std::auto_ptr exception_; }; } // namespace detail template class future; template class promise { public: promise() : return_value_(new detail::return_value) { } void operator()(T t) // Fulfil { return_value_->set(t); } template void fail(E e) { return_value_->fail(e); } private: friend class future; boost::shared_ptr > return_value_; }; template class future { private: public: future(promise& p) : return_value_(p.return_value_) { } T operator()() const // Await { return return_value_->get(); } private: boost::shared_ptr > return_value_; }; #endif // FUTURE_HPP