Monday, October 17, 2016

Resumable functions in VC++ 2015

Resumable functions are co-routines. People are expecting C++17 proposal define its usage to be as simple as async/await in C# language.

How to enable resumable functions in VC++2015:

  • Add /await option

Visual C++ 2015 has a new compiler option called /await that can be used to write and call resumable functions, and you would need to manually add it via the Additional Options box under the C/C++ property page.

  • Change  /ZI option into /Zi option in order to disable the debugger’s edit-and-continue feature
  • Disable SDL checks with the /sdl- option
  • Avoid the /RTC option


Here gives C++ code snippets of resumable functions and usage.

The async function below will execute the function asynchronously, typically in a separate thread, and return a future that will hold the result of the call when it’s completed.


#include <future>
#include <iostream>
#include <experimental\resumable>

using namespace std::chrono; 

std::future<int> sum_async(int x, int y)
{
  return std::async([x, y] 
  {
    std::this_thread::sleep_for(2s);
    return x + y; 
  });
}



Now, here’s how this method can be called. The await keyword calls that method asynchronously and waits until the method executes to completion. And then control goes to the next line of code.


std::future<void> call_sum_async(int x, int y)
{
  std::cout << "** async func - before call" << std::endl;
  auto sum = await sum_async(x, y);
  std::cout << "** async func - after call" << std::endl;
}

void main_async()
{
  std::cout << "<< main func - before call" << std::endl;
  auto result = call_sum_async(7, 9);
  std::cout << "<< main func - after call" << std::endl;

  {
    using namespace std::chrono;
    std::cout << "<< main func - before sleep" << std::endl;
    std::this_thread::sleep_for(3s);
    std::cout << "<< main func - after sleep" << std::endl;
  }
  result.get();
  std::cout << "<< main func - after get" << std::endl;
}

No comments:

Post a Comment