Reputation: 201
According to what's written about future in "the c++ programming language 4th edition"
§5.3.5.1 page 120:
If the value isn’t there yet, our thread is blocked until it arrives.
Meaning that get() is a blocking method.
Later in §5.3.5.2 page 122 packaged_task is explained, and the following code sample is given:
double accum(double* beg, double* end, double init)
// compute the sum of [beg:end) starting with the initial value init
{
return accumulate(beg,end,init);
}
double comp2(vector<double>& v)
{
using Task_type = double(double*,double*,double); // type of task
packaged_task<Task_type> pt0 {accum}; // package the task (i.e., accum)
packaged_task<Task_type> pt1 {accum};
future<double> f0 {pt0.get_future()}; // get hold of pt0’s future
future<double> f1 {pt1.get_future()}; // get hold of pt1’s future
double* first = &v[0];
thread t1 {move(pt0),first,first+v.size()/2,0}; // start a thread for pt0
thread t2 {move(pt1),first+v.size()/2,first+v.size(),0}; // start a thread for pt1
// ...
return f0.get()+f1.get(); // get the results
}
This makes sense, since according to the quote the following program won't return until the 2 threads in comp2() function finished even without calling join() on them since the thread that called comp2() will wait for the futures until they get() their value:
int main()
{
vector<double> v {1.1, 8.3, 5.6};
double res = comp2(v);
return 0;
}
Unfortunately, this doesn't happen like I thought, and I less I call join() on the 2 threads in comp2(), a run-time error will be thrown.
Could someone explain me what am I missing here and why get() doesn't block ?
Upvotes: 3
Views: 4067
Reputation: 1844
I've debugged your code with gdb, your runtime error is happening in std::thread destructor. You have to either detach
or join
them before they're destructed, e.g:
t1.detach();
t2.detach();
inside comp2()
.
This will net your expected behaviour.
Upvotes: 1