Boost.Coroutine 触ってみた
Boost.Coroutine が採用されたということで簡単に触ってみました。
- ソースコード:http://ok73.funpic.de/boost-coroutine.zip.
- ドキュメント:http://ok73.ok.funpic.de/boost/libs/coroutine/doc/html/
ソースコードはどこにあるか分からなかったので ML に載っていたものを使用しました。
間違っていたらすみません。
とりあえず、Hello, World でも。
[ソース]
#include <boost/coroutine/coroutine.hpp> #include <iostream> typedef boost::coroutines::coroutine<void()> coroutine_type; void hello_world1(coroutine_type::caller_type& coroutine){ std::cout << "Hello"; coroutine(); std::cout << ", "; coroutine(); std::cout << "World" << std::endl; coroutine(); throw std::runtime_error("abc"); } void hello_world2(coroutine_type::caller_type& coroutine){ while(1){ std::cout << "Hello"; coroutine(); std::cout << ", "; coroutine(); std::cout << "World" << std::endl; coroutine(); } } int main(){ coroutine_type coroutine1(hello_world1); try{ coroutine1(); coroutine1(); coroutine1(); coroutine1(); coroutine1(); } catch(std::exception const& e){ std::cout << e.what() << std::endl; } std::cout << "-----" << std::endl; coroutine_type coroutine2(hello_world2); for(int i = 0 ; i < 10 ; ++i){ coroutine2(); } return 0; }
[出力]
Hello, World abc ----- Hello, World Hello, World Hello, World Hello,
こんな感じ。
関数を呼び出しているだけなのでだいぶすっきりとしていますね。
あと Boost.Coroutine を使うためには予め Boost.Context をビルドしておく必要があります。