Created
October 28, 2017 07:21
-
-
Save yizhang82/28842f7dbae34b59fcd7b4d74b4a19d4 to your computer and use it in GitHub Desktop.
Simple C++ coroutine example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
please share detailed compilation procedure for this cpp file.
How can i compile the above code in ubuntu?
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).
dead lock will happend?
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
In order to compile the code, you need to pass /await as a compiler switch