繁体   English   中英

c ++ future.get()没有阻塞

[英]c++ future.get() is not blocking

根据“c ++编程语言第4版”中有关未来的内容
§5.3.5.1第120页:

如果该值尚未存在,则我们的线程将被阻塞,直到它到达。

这意味着get()是一种阻塞方法。

稍后在§5.3.5.2第122页中解释了packaged_task ,并给出了以下代码示例:

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
} 

这是有道理的,因为根据引用,以下程序将不会返回,直到comp2()函数中的2个线程完成,即使没有调用join() ,因为调用comp2()的线程将等待未来的 s直到它们get()他们的价值:

int main()
{
    vector<double> v {1.1, 8.3, 5.6};
    double res = comp2(v);
    return 0;
}

不幸的是,这并不像我想的那样发生,而且我在comp2()中的2个线程上调用join() ,会抛出运行时错误。

有人可以解释一下我在这里缺少什么以及为什么get()不会阻止?

我用gdb调试了你的代码,你的运行时错误发生在std :: thread析构函数中。 你必须在它们被破坏之前detachjoin它们,例如:

t1.detach();
t2.detach();

comp2()

这将净化您的预期行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM