您的位置:首页 > 编程语言 > C语言/C++

c++中boost协程5种使用实例

2017-12-19 23:00 295 查看
[java]
view plain
copy

#include <iostream>  
#include <boost/coroutine/all.hpp>    
  
  
using namespace boost::coroutines;  
  
//coroutine函数  
void cooperative(coroutine<void>::push_type &sink)  
{  
    std::cout << "Hello";  
  
    //之所以能够执行是因为重载了操作符()  
    //返回main()函数继续运行  
    sink();  
  
    std::cout << "world";  
  
    //执行完毕,返回main继续执行  
}  
  
int main()  
{  
    //c++11新特性:统一初始化  
    //source对象由于是pull_type类型,所以会马上调用cooperative, push_type类型不会立即执行  
    coroutine<void>::pull_type source{ cooperative };  
      
    std::cout << ", ";  
  
    //返回cooperative函数继续执行  
    source();  
  
    std::cout << "!";  
  
    std::cout << "\n";  


输出结果



[java]
view plain
copy

#include <functional>  
#include <iostream>  
#include <boost/coroutine/all.hpp>  
  
  
using boost::coroutines::coroutine;  
  
void cooperative(coroutine<int>::push_type &sink, int i)  
{  
    int j = i;  
  
    //调用main  
    sink(++j);  
  
    //调用main  
    sink(++j);  
  
    std::cout << "end\n";  
}  
  
int main()  
{  
    using std::placeholders::_1;  
  
    //传入一个参数,初始值为0  
    coroutine<int>::pull_type source{ std::bind(cooperative, _1, 0) };  
    std::cout << source.get() << '\n';  
  
    //调用cooperative  
    source();  
    std::cout << source.get() << '\n';  
  
    //调用cooperative  
    source();  




[java]
view plain
copy

#include <tuple>  
#include <string>  
#include <iostream>  
#include <boost/coroutine/all.hpp>  
  
  
using boost::coroutines::coroutine;  
  
void cooperative(coroutine<std::tuple<int, std::string>>::pull_type &source)  
{  
    auto args = source.get();  
    std::cout << std::get<0>(args) << " " << std::get<1>(args) << '\n';  
  
    source();  
  
    args = source.get();  
    std::cout << std::get<0>(args) << " " << std::get<1>(args) << '\n';  
}  
  
int main()  
{  
    coroutine<std::tuple<int, std::string>>::push_type sink{ cooperative };  
  
    //通过tuple传递多个参数  
    sink(std::make_tuple(0, "aaa"));  
  
    //通过tuple传递多个参数  
    sink(std::make_tuple(1, "bbb"));  
  
    std::cout << "end\n";  
}  



#include <iostream>
#include <cstdlib>

#include <boost/coroutine2/all.hpp>

int main()
{
int i = 0;
boost::coroutines2::coroutine< void >::push_type sink(
[&](boost::coroutines2::coroutine< void >::pull_type & source) {
std::cout << "inside coroutine-fn" << std::endl;
});
sink();

std::cout << "\nDone" << std::endl;

return EXIT_SUCCESS;

}



#include <stdexcept>
#include <iostream>
#include <boost/coroutine/all.hpp>

using boost::coroutines::coroutine;

void cooperative(coroutine<void>::push_type &sink)
{
//返回main
sink();
throw std::runtime_error("error");
}

int main()
{
coroutine<void>::pull_type source{ cooperative };
try
{
//调用cooperative
source();

//捕获抛出的异常std::runtime_error
}
catch (const std::runtime_error &e)
{
std::cerr << e.what() << '\n';
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: