Link L
Link L

Reputation: 439

why do boost futures return different values?

I want to write a code where I use boost futures and threads to compute several functions in parallel:

The function is named 'function' that takes on 'inputs', and I want to store the function return values in a vector named 'results'

CODE 1 (part only of the main code):

    for (int i = 0; i < max_iter; i++) {
          boost::shared_future<double>> future = boost::async(boost::launch::async,boost::bind(&function,input));
          results[i] = future.get();}

But I would like to let the threads run in parallel, so I tried doing this code which stores the futures in a vector and then gets the results as soon as all futures are ready. I used the wait_for_all function from boost to wait for threads to get finished..

CODE 2 (part only of the main code):

    for (int i = 0; i < max_iter; i++) {
                      boost::shared_future<double>> future = boost::async(boost::launch::async,boost::bind(&function,input));
                      future_buffer.push_back(future);

    boost::wait_for_all(future_buffer.begin(), future_buffer.end())

    for (int l = 0; l < max; l++) {
        results[l] = future_buffer[l].get()
    }

I got to comply both CODE 1 and CODE 2, but am getting different results... I checked and CODE 1 gives the right results but CODE 2 doesn't, and I couldn't figure out why?... what am I missing here...?

Upvotes: 0

Views: 75

Answers (1)

Caleth
Caleth

Reputation: 62704

You don't show the body of function, so we can't know for sure. But there's a obvious guess.

Your first code is doing everything sequentially. It also has a large amount of overhead of starting threads and then immediately waiting for them to end. It is otherwise the same as

for (int i = 0; i < max_iter; i++) {
    results[i] = function(input);
}

Your second code is (probably) doing things in parallel. It sounds like you have data shared between all the calls to function, and change in one thread invalidate the data seen in another.

Upvotes: 1

Related Questions