Skip to content

Instantly share code, notes, and snippets.

@yizhang82
Created October 28, 2017 07:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yizhang82/28842f7dbae34b59fcd7b4d74b4a19d4 to your computer and use it in GitHub Desktop.
Save yizhang82/28842f7dbae34b59fcd7b4d74b4a19d4 to your computer and use it in GitHub Desktop.
Simple C++ coroutine example
#include <future>
#include <iostream>
using namespace std;
future<int> async_add(int a, int b)
{
auto fut = std::async([=]() {
int c = a + b;
return c;
});
return fut;
}
future<int> async_fib(int n)
{
if (n <= 2)
co_return 1;
int a = 1;
int b = 1;
// iterate computing fib(n)
for (int i = 0; i < n - 2; ++i)
{
int c = co_await async_add(a, b);
a = b;
b = c;
}
co_return b;
}
future<void> test_async_fib()
{
for (int i = 1; i < 10; ++i)
{
int ret = co_await async_fib(i);
cout << "async_fib(" << i << ") returns " << ret << endl;
}
}
int main()
{
auto fut = test_async_fib();
fut.wait();
return 0;
}
@sfinktah
Copy link

In order to compile the code, you need to pass /await as a compiler switch

@mithunshashidhara
Copy link

please share detailed compilation procedure for this cpp file.

@nishantd01
Copy link

How can i compile the above code in ubuntu?

@jzhou77
Copy link

jzhou77 commented May 22, 2019

co_return and co_await require compilers support c++20 standard (see https://en.cppreference.com/w/cpp/keyword and https://en.cppreference.com/w/cpp/compiler_support).

@wycharry
Copy link

wycharry commented Aug 1, 2019

dead lock will happend?

@RoyBellingan
Copy link

GCC 10.1 gives

error: unable to find the promise type for this coroutine
39| int ret = co_await async_fib(i);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment