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

问题描述 投票:0回答:1
#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

哪个更好?

c++ multithreading c++11 promise future
1个回答
13
投票

首先获取 future,然后将 Promise 移至线程中。

std::future<int> f() {
  std::promise<int> p;
  auto r=p.get_future();
  std::async(t1, move(p)); // THIS IS STUPID because it blocks until the thread finishes
  return r;
}

当然这是愚蠢的,因为你使用

async
会阻塞,直到任务完成。但这是
promise
的正确使用。

共享承诺是不好的,它应该具有唯一的所有权,因为只有一个人应该设定它的价值。无论是谁都应该拥有自己的一生。

离开它之后,你就无法再从中获得未来。

© www.soinside.com 2019 - 2024. All rights reserved.