Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
xmllmx Avatar asked Jan 04 '23 20:01

xmllmx


1 Answers

First get the future, then move the promise into the thread.

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

Of course this is stupid, because your use of async blocks until the task is complete. But it is the proper use of promise.

Sharing a promise is bad, it should have unique ownership as only one should set its value. And whomever that is should own its lifetime.

After moving from it, you can no longer get a future from it.

like image 92
Yakk - Adam Nevraumont Avatar answered Jan 13 '23 15:01

Yakk - Adam Nevraumont