gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:10:34 25 4
gpt4 key购买 nike

通过打包任务创建一个线程并返回一个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 保证 vector 与 main 线程同步(在 join 之前),但我不确定打包任务参数的状态(通过引用传递)。

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

最佳答案

int arg=0;

发生在我们启动线程thr,因为它是sequenced-before它。

arg = 10;

由于 .get() 调用,此 happens-before vec 已初始化:

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 之类的行为。

关于c++ - 打包任务参数是否存在数据竞争?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53712190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com