【发布时间】:2016-04-05 18:24:47
【问题描述】:
所以我写了下面这段代码。它有时会得到:
段错误::11
但有时不会。你能解释一下为什么吗?
我也对以下问题感到好奇。
一般来说,c++如何将线程分配给/c++何时执行launch::async和launch::defferred函数?如果是future<void>,std::wait 比 std::get 有什么缺点吗?
std::future<void>r1, r2, r3, r4, ret;
//sometimes seg fault, sometimes pass
void f(int id, int t) {
printf("call f(%d)\n", id);
int ans=0;
if (id == 3) {
printf("wait 3\n");
if (r1.valid()) r1.wait();
}
if (id == 4) {
printf("wait 4\n");
if (r1.valid()) r1.wait();
}
printf("start f(%d)\n",id);
cnt[id]++;
for (int i=1;i<=t;i++) {
ans++;
}
printf("end f(%d)\n", id);
}
int main() {
r3=async(f, 3, 1e8);
r4=async(f, 4, 1);
r1=async(f, 1, 1e8);
r2=async(f, 2, 1e2);
ret=async([&]() { r1.wait();r2.wait();r3.wait();r4.wait(); printf("cnt=%d,%d,%d,%d\n", cnt[1],cnt[2],cnt[3],cnt[4]); });
return 0;
}
【问题讨论】:
-
声明
cnt?基于 1 的数组索引是一个值得关注的问题。 -
什么是cnt?数数?为什么不叫它计数?这在任何地方都没有定义。如果有一些有意义的变量名会有所帮助。如果
id==4 or 3,您正在引用r1。使用异步调用,不能保证 r1 已初始化,因此调用 r1.valid() 可能会导致 seg 错误。 -
@ChristopherSchneider 您可以在默认构造的未来调用
valid()。它只返回false。 -
你需要发一个MCVE,有太多的可能性让别人猜到你的代码的其余部分
标签: c++ multithreading asynchronous future