I'm learning the C++11 features and wrote some code along the following lines
#include <vector>
#include <thread>
using std::thread;
using std::vector;
double Computation(int arg)
{
// some long-running computation
return 42.0;
}
double ConcurrentComputations()
{
const int N = 8; // number of threads
vector<thread> thr;
vector<double> res(N);
const int arg = 123456; // something or other
// Kick off threads which dump their results into res
for(int i=0; i<N; ++i)
thr.push_back(thread ([&res, i, arg]()
{ res[i] = Computation(arg); } ));
// Wait for them to finish and get results
double sum = 0;
for(int i=0; i<N; ++i) {
thr[i].join();
sum += res[i];
}
return sum;
}
Looking at it again in the cold light of day, I don't think I really should have been taking a reference to a vector
in the lambda function and dumping data into it. I was thinking of the vector as a regular array and relying on the implementation of operator[]
to simply add i
to &res.front()
(maybe I should have captured &res.front()
instead, and now that I've read further in Stroustrup 4ed I can see I should maybe use futures and promises).
Nevertheless, my question is, is it reasonable to think that in practice I can get away with the code that I wrote?