打包任务参数是否存在数据竞争?

Is there a data race on packaged task arguments?

通过打包任务创建线程,返回std::vector

#include <iostream>
#include <future>
#include <thread>
#include <vector>

std::vector<int> func(int &arg)
{
    std::vector<int> v = {1,2,3,4};

    arg = 10;

    return v;
}

int main()
{
    std::packaged_task<std::vector<int>(int &)> pt{func};
    auto fut = pt.get_future();

    int arg = 0;
    std::thread thr{std::move(pt), std::ref(arg)};

    auto vec = fut.get();

    std::cout << arg << std::endl;  // data race here ?

    thr.join();
}

std::future保证向量与main线程同步(在join之前), 但我不确定打包任务参数(通过引用传递)的状态。

所以问题是 arg 上是否存在数据竞争?

int arg=0;

这个happens-before我们启动线程thr,因为它是sequenced-before它。

arg = 10;

这个 happens-before vec 被初始化,由于 .get() 调用:

auto vec=fut.get();

前序

std::cout << arg << std::endl;

所以我看不到这里有数据竞争。

虽然不具有权威性,但cpp reference声称:

The promise is the "push" end of the promise-future communication channel: the operation that stores a value in the shared state synchronizes-with (as defined in std::memory_order) the successful return from any function that is waiting on the shared state (such as std::future::get).

std::async也有类似的词。我相信 packaged_task 也有类似的保证;毕竟,它旨在用作原语来帮助实现您自己的 std::async 类行为。