Skip to content

Instantly share code, notes, and snippets.

@DBJDBJ
Forked from yizhang82/coroutine-simple.cpp
Last active September 6, 2018 13:32
Show Gist options
  • Save DBJDBJ/25a6058010e067ace7b4f76eefa180a4 to your computer and use it in GitHub Desktop.
Save DBJDBJ/25a6058010e067ace7b4f76eefa180a4 to your computer and use it in GitHub Desktop.
Simple C++ coroutine example
/*
until C++20 to build this with CL (MSVC)
/await compiler switch is required
*/
#include <future>
#include <iostream>
#ifndef __cpp_coroutines
#error __FILE__ " requires coroutines..."
#endif
// do not do anonymous namespaces in headers
namespace {
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(std::size_t max_fibi )
{
for (std::size_t i = 1; i < max_fibi; ++i)
{
int ret = co_await async_fib(i);
cout << "async_fib(" << i << ") returns " << ret << endl;
}
}
} // namespace
int main()
{
auto fut = test_async_fib();
fut.wait();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment