修改 std::future 的 lambda 中引用捕获的值

Modify values captured by reference in lambda of std::future

有人可以向我解释为什么在 std::future 的 lambda 中修改通过引用捕获的值不会产生我期望的结果吗?见代码:

const int runs{ 1000 };
for (int run = 0; run < runs; ++run)
{
    const int num{ 4 };
    std::vector<bool> res(num, false);
    std::vector<std::future<void>> futs(num);
    for (int i = 0; i < num; ++i)
    {
        futs[i] = std::async(std::launch::async, [&res, i]
        {
            res[i] = true;
        });
    }
    for (auto& fut : futs) fut.wait();
    for (auto v : res) // I expect all values of res to be set to true.
    {
        if (!v) std::cerr << "Bad!!!\n"; // But this happens!
    }
}

您有导致未定义行为的数据竞争。 vector<bool> 的不同项目不应由不同的线程同时修改。

你可以阅读它here

Does not guarantee that different elements in the same container can be modified concurrently by different threads.

here

Notwithstanding [res.on.data.races], implementations are required to avoid data races when the contents of the contained object in different elements in the same container, excepting vector, are modified concurrently.