Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jan 26, 2018

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

@mithunshashidhara

This comment has been minimized.

Copy link

commented Jul 24, 2018

please share detailed compilation procedure for this cpp file.

@nishantd01

This comment has been minimized.

Copy link

commented Aug 24, 2018

How can i compile the above code in ubuntu?

@jzhou77

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Aug 1, 2019

dead lock will happend?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.