gpt4 book ai didi

c++ - 异步运行的函数的返回类型应该是什么

转载 作者:搜寻专家 更新时间:2023-10-31 02:18:06 25 4
gpt4 key购买 nike

我只是尝试这个样本来了解 future 和 promise 。

void func(std::promise<int>& p) {
p.set_value (0);
}

int main ()
{
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread t(func, std::ref(p));
int x = fut.get();

t.join();
return 0;
}

如果func的返回类型可以吗?是无效的吗?如果是,返回类型可以是void吗?如果它与 std::async 一起使用

 std::future<int> f = std::async(std::launch::async,  func);

async的返回是否推导为std::future< int >如果 func 的返回类型是void

请说明负责设置 promise 的函数的返回类型。

另外,func 的设计是否应该基于它可以的使用方式?

最佳答案

在第一个示例中,std::thread 运行的函数构造函数可以返回一个值,也可以不返回一个值,该值被忽略。

std::async调用所提供函数的返回值(由 std::result_of 确定)设置返回的模板类型 std::future :

// function returns an int so std::async() returns a std::future<int>
std::future<int> fut = std::async(std::launch::async, []{ return 1; });

根据C++11标准:

30.6.8 函数模板异步

4 Returns: An object of type future<typename result_of<F(Args...)>::type> that refers to the shared state created by this call to async.

所以在你的第一个例子中,函数的返回类型是什么并不重要,因为它是设置 std::promise 的函数体。 ,而不是返回值。

带有 std::async() ,但是,return 语句必须将共享值返回给 std::future .

关于c++ - 异步运行的函数的返回类型应该是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34840754/

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