Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ promise/future: Which to return from a function?

I have a function that returns a reference to a std::promise:

std::shared_ptr<std::promise<void>> play();

(More info: The function plays media on some device, and the return value represents when this playing is complete. If play is called a second time, a value is set on the promise returned the first time, and a new promise is created and returned for this second call)

The caller can then catch the value and wait on the future:

auto this_future = play()->get_future();
this_future.wait();

Does it make sense to return a reference to the promise, or should I return the future instead, so that the calling function does not have to call get_future()?

like image 663
Scott M Avatar asked Apr 15 '15 17:04

Scott M


1 Answers

Since the implementation of play() is not posted, I'd say most likely you should return the future, and the function should work with the promise itself, most likely in a different thread. The rationale for this design stems from the fact that promise is a producer end, and future is a consumer end — so the function would produce a value, set it through the promise instance, which will notify the future that result has arrived through get.

However, note that, you don't have to return a std::shared_ptr<std::future<T>> — just std::future<T> would work great.

like image 101
Nawaz Avatar answered Oct 27 '22 08:10

Nawaz