0

I would like to implement a method like this:

boost::unique_future<int> foo()
{
    return defer([=] // call this lambda on boost::unique_future<int>::get();
    {
         return prime(10);
    });
}

I know of boost::promise and boost::packaged_task and set_wait_callback, however since the returned future takes a reference to either this will not work?

I know there is std::async and std::launch::sync, but how can emulate it using boost and vs2010?

std::unique_future<int> foo()
{
    return std::async(std::launch::sync, [=] 
    {
         return prime(10);
    });
}
ronag
  • 49,529
  • 25
  • 126
  • 221

2 Answers2

2

You can use set_wait_callback, you just have to dynamically allocate the promise, and delete it in the callback after you set the value:

#include <boost/thread.hpp>
#include <iostream>

void callback(boost::promise<int>&p) {
    std::cout<<"callback"<<std::endl;
    p.set_value(42);
    delete &p;
}

boost::unique_future<int> f()
{
    boost::promise<int> *p=new boost::promise<int>;
    p->set_wait_callback(callback);
    return p->get_future();
}

int main()
{
    boost::unique_future<int> uf(f());
    std::cout<<"main()"<<std::endl;
    int val=uf.get();
    std::cout<<"val="<<val<<std::endl;
}
Anthony Williams
  • 66,628
  • 14
  • 133
  • 155
  • One mayor problem. If get() is not called then the promise is leaked. – ronag Feb 19 '12 at 23:04
  • If you use a shared_ptr then you will get a circular dependency and it will still leak. – ronag Feb 20 '12 at 10:35
  • You're right. The best solution would be to modify the boost code to do what you want. – Anthony Williams Feb 20 '12 at 13:46
  • I solved it with `boost::detail::future_object` and a `reintepret_cast` trick to create a `boost::unique_future`. Very ugly, but it works without modifying boost. – ronag Feb 20 '12 at 14:06
  • Could you explain your solution with a bit more detail? I think I ran into a similar issue here http://stackoverflow.com/questions/13066667/pattern-for-future-conversion and I'd really like to see how you managed to call the hidden c'tor of boost::unique_future to store your own future_object there. – duselbaer Oct 25 '12 at 11:44
0

You can use this ticket's code : https://svn.boost.org/trac/boost/ticket/4710

Akira Takahashi
  • 2,912
  • 22
  • 107
  • Though that will just execute the task right away on the other thread, I only want it to execute on `get`. – ronag Jan 23 '12 at 07:49