#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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With