gpt4 book ai didi

c++ - 如何将 std::promise 传递到线程中?通过 std::move 还是通过 std::shared_ptr?

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:21 24 4
gpt4 key购买 nike

#include <future>

using namespace std;

void t1(promise<int> p)
{
this_thread::sleep_for(chrono::seconds(5));
p.set_value(0);
}

void t2(shared_ptr<promise<int>> p)
{
this_thread::sleep_for(chrono::seconds(5));
p->set_value(0);
}

future<int> f1()
{
promise<int> p;
async(t1, move(p));

return p.get_future();
}

future<int> f2()
{
auto p = make_shared<promise<int>>();
async(t2, p);

return p->get_future();
}

int main()
{
f1().get();
f2().get();

return 0;
}

我的问题是:

如何将 std::promise 对象传递到线程中,通过 std::move 或通过 std::shared_ptr?

哪个更好?

最佳答案

首先获取 future ,然后将 promise 移动到线程中。

std::future<int> f() {
std::promise<int> p;
auto r=p.get_future();
std::async(t1, move(p));
return r;
}

当然这是愚蠢的,因为您对 async 的使用会阻塞直到任务完成。但这是 promise 的正确使用。

共享一个 promise 是不好的,它应该有唯一的所有权,因为只有一个人应该设置它的值。无论是谁,都应该拥有自己的生命周期。

离开它之后,你无法再从它那里获得 future 。

关于c++ - 如何将 std::promise 传递到线程中?通过 std::move 还是通过 std::shared_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41325897/

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