gpt4 book ai didi

C++ future.get() 不阻塞

转载 作者:太空狗 更新时间:2023-10-29 23:02:10 24 4
gpt4 key购买 nike

根据《c++程序设计语言第4版》中关于future的内容
§5.3.5.1 第 120 页:

If the value isn’t there yet, our thread is blocked until it arrives.

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

稍后在§5.3.5.2 page 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() 的线程将等待 future,直到它们 get() 它们的值:

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

不幸的是,这并没有像我想象的那样发生,我也很少调用 join()comp2() 中的 2 个线程上,将抛出运行时错误。

有人可以解释一下我在这里遗漏了什么以及为什么 get() 不阻塞吗?

最佳答案

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

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

comp2() 中。

这将达到您预期的行为。

关于C++ future.get() 不阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com