C ++异步段错误

时间:2016-04-05 18:24:47

标签: c++ multithreading asynchronous future

所以我写了下面这段代码。它有时会得到:

  

段故障:: 11

但有时却没有。你能解释一下原因吗?

我也对以下问题感到好奇。 一般来说,c ++如何为/ c何时执行launch::asynclaunch::defferred函数分配线程?如果std::waitstd::getfuture<void>会不会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; }

apply plugin: 'maven'

uploadArchives {
    repositories {
        mavenDeployer {
            repository(url: "http://repo"){
                authentication(userName: "yankee", password: "doodle")
            }
            snapshotRepository(url: "http://repo-snapshotRepository"){
                authentication(userName: "yankee", password: "doodle")
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

  

有时会得到:

     

段故障:: 11

     

但有时候并没有。你能解释一下原因吗?

我假设cnt被正确声明,因此没有越界访问。如果是这种情况,那么我认为这里的问题是std::future对象不是线程安全的,因此对r1.valid()r1.wait()的调用与r1的调用竞争{1}}发生在main。这样的数据竞争会导致不确定的行为。

看起来你应该移动线

r1=async(f, 1, 1e8);

main的开头。然后,在r1std::async的{​​{1}}调用之前,将对r3的写入进行排序。 r4的调用与std::async的相应调用同步。因此,f的写入发生在r1中对r1.wait的调用之前。 f成员函数为future::wait,因此两个线程可以在不竞争的情况下同时调用它。

对于更复杂的情况,您可以使用const(如果您愿意,可以先获取std::packaged_task并稍后启动)或std::future

  

一般来说,c ++如何为/ c何时执行std::promiselaunch::async函数分配线程?

如果您在选择时launch::defferred选择std::async选择使用哪种策略,那么答案就是未指定。