Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ futures/promises like javascript?

Tags:

I've been writing some javascript and one of the few things I like about the environment is the way it uses promises/futures to make handlers for asynchronous events.

In C++ you have to call .get on a future and it blocks until the result of the future is available but in Javascript you can write .then(fn) and it will call the function when the result is ready. Critically it does this in the same thread as the caller at a later time so there are no thread synchronization issues to worry about, at least not the same ones as in c++.

I'm thinking in c++ something like -

auto fut = asyncImageLoader("cat.jpg");
fut.then([](Image img) { std::cout << "Image is now loaded\n" << image; });

Is there any way to achieve this in c++? Clearly it will need some kind of event queue and event loop to handle dispatching the callbacks. I could probably eventually write the code to do most of this but wanted to see if there was any way to achieve the goal easily using standard facilities.

like image 950
jcoder Avatar asked Jan 07 '14 14:01

jcoder


People also ask

Are futures and promises the same?

Futures and promises are pretty similar concepts, the difference is that a future is a read-only container for a result that does not yet exist, while a promise can be written (normally only once).

What is the alternative of promise in JS?

Error Handling in Async/Await: For a successfully resolved promise, we use try and for rejected promise, we use catch. To run a code after the promise has been handled using try or catch, we can . finally() method.

What are the 3 states of a JavaScript promise?

A Promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation was completed successfully. rejected: meaning that the operation failed.

Are promises part of JavaScript?

As of ES6 (ES2015), promises are built into the Javascript specification and implementations to that spec. Before that, there were separate (outside of the language itself) implementations.


1 Answers

A .then function for std::future has been proposed for the upcoming C++17 standard.

Boost's implementation of future (which is compliant with the current standard, but provides additional features as extensions) already provides parts of that functionality in newer versions (1.53 or newer).

For a more well-established solution, take a look at the Boost.Asio library, which does allow easy implementation of asynchronous control flows as provided by future.then. Asio's concept is slightly more complicated, as it requires access to a central io_service object for dispatching asynchronous callbacks and requires manual management of worker threads. But in principle this is a very good match for what you asked for.

like image 102
ComicSansMS Avatar answered Sep 29 '22 10:09

ComicSansMS