Last active
August 29, 2015 14:13
-
-
Save daeyun/db3bd9c8255e360426a6 to your computer and use it in GitHub Desktop.
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
/** | |
* C++11 coroutine example using Boost.Coroutine | |
* Created by daeyun on 1/13/15. | |
*/ | |
#include <iostream> | |
#include <boost/coroutine/all.hpp> | |
template <typename T> | |
using coro = boost::coroutines::asymmetric_coroutine<T>; | |
using std::cout; | |
using std::endl; | |
struct FibState { | |
FibState() { cout << "FibState()" << endl; } | |
~FibState() { cout << "~FibState()" << endl; } | |
int prev[2]{1, 0}; | |
int current; | |
}; | |
int main() { | |
coro<int>::pull_type source([&](coro<int>::push_type& sink) { | |
FibState fib; | |
while (true) { | |
fib.current = fib.prev[0] + fib.prev[1]; | |
cout << "(generating " << fib.current << "..)" << endl; | |
// Similar to `yield` in Python | |
sink(fib.current); | |
fib.prev[0] = fib.prev[1]; | |
fib.prev[1] = fib.current; | |
} | |
cout << "Not printed" << endl; | |
}); | |
const int kFibLimit = 100; | |
cout << "Fibonacci numbers less than " << kFibLimit << ":" << endl; | |
for (auto i : source) { | |
if (i > kFibLimit) break; | |
cout << i << endl; | |
} | |
cout << "End of main()" << endl; | |
return 0; | |
} | |
/* Output: | |
FibState() | |
(generating 1..) | |
Fibonacci numbers less than 100: | |
1 | |
(generating 1..) | |
1 | |
(generating 2..) | |
2 | |
(generating 3..) | |
3 | |
(generating 5..) | |
5 | |
(generating 8..) | |
8 | |
(generating 13..) | |
13 | |
(generating 21..) | |
21 | |
(generating 34..) | |
34 | |
(generating 55..) | |
55 | |
(generating 89..) | |
89 | |
(generating 144..) | |
End of main() | |
~FibState() | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment