dimanche 25 décembre 2016

How to pass std::promise into a thread? by std::move or by std::shared_ptr?

#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;
}

My question is:

How to pass a std::promise object into a thread, by std::move or by std::shared_ptr?

Which is better?

Aucun commentaire:

Enregistrer un commentaire