Visual C++ 2015 – Resumable Functions
Visual C++ 2015 includes a general purpose solution to implement resumable functions based on the concept of coroutines. A coroutine is a generalized routine entity which supports operations like suspend and resume in addition to the traditional invoke and return operations.
These resumable functions are being proposed for inclusion in ISO C++17.
For the VC++ 2015 Preview, the feature only works for 64-bit targets, and requires adding the /await switch to your compiler command-line.
Such resumable functions have several use cases:
- Asynchronous operations
- Generator pattern
- Reactive Streams
Here is a simple example demonstrating an asynchronous operation:
#include <future> #include <thread> #include <experimental\resumable> using namespace std; using namespace std::chrono; // this could be some long running computation or I/O future<int> calculate_the_answer() { return async([] { this_thread::sleep_for(1s); return 42; }); } // Here is a resumable function future<void> coro() { printf("Started waiting... \n"); auto result = __await calculate_the_answer(); printf("got %d. \n", result); } int _tmain(int argc, _TCHAR* argv[]) { coro().get(); }
The important line here is line 17. The function calculate_the_answer() is an asynchronous function which immediately returns by returning a future