2

私はプロジェクトでC++ 11を使用していますが、ここに関数があります:

void task1(int* res) {
    *res = 1;
}

void task2(int* res) {
    *res = 2;
}

void func() {
    std::vector<int> res(2, 0); // {0, 0}
    std::thread t1(task1, &res[0]);
    std::thread t2(task2, &res[1]);
    t1.join();
    t2.join();
    return res[0] + res[1];
}

機能はその通りです。std::vectorスレッドのすべての結果を格納するがあることがわかります。

私の質問は:std::vector偽の共有を引き起こす可能性がありますか? std::vector可能であれば、スレッドの結果を保存するために使用しているときに誤った共有を回避する方法はありますか?

4

2 に答える 2