Boost 协程

Boost 协程

flyfish

什么是协程

Donald Knuth说,Melvin Conway在1958年发明了“coroutine”这个词

Coroutines是计算机程序组件,它可以为非抢占式的多任务处理子程序,通过允许在某些位置暂停和恢复执行的多个入口点。
Coroutines非常适合于实现熟悉的程序组件,例如协作任务、异常、事件循环、迭代器、无限列表和管道。

Comparison with subroutines
Coroutine与Subroutine的对比

Subroutines are special cases of … coroutines.

— Donald Knuth

C++11版本 Boost.Coroutine2
这里用的是Boost.Coroutine
简单示例

#include "stdafx.h"

#include "boost/coroutine/all.hpp"
#include 

void cooperative(boost::coroutines::coroutine::push_type &sink)
{
    std::cout << "Hello";
    sink();
    std::cout << "world";
}

int _tmain(int argc, _TCHAR* argv[])
{
    boost::coroutines::coroutine::pull_type source{ cooperative };
    std::cout << ", ";
    source();
    std::cout << "!\n";
    return 0;
}

Hello, world!

返回值示例

#include 
#include 
#include 

void cooperative(boost::coroutines::coroutine<int>::push_type &sink, int i)
{
    int j = i;
    sink(++j);
    sink(++j);
    std::cout << "end\n";
}

int _tmain(int argc, _TCHAR* argv[])
{
    using std::placeholders::_1;
    boost::coroutines::coroutine<int>::pull_type source{ std::bind(cooperative, _1, 0) };
    std::cout << source.get() << '\n';
    source();
    std::cout << source.get() << '\n';
    source();

    return 0;
}

输出
1
2
end

传递参数示例

#include 
#include 
#include 
#include 

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 };
    sink(std::make_tuple(0, "aaa"));
    sink(std::make_tuple(1, "bbb"));
    std::cout << "end\n";
}

输出
0 aaa
1 bbb
end

异常处理示例

#include 
#include 
#include 

using boost::coroutines::coroutine;

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

int main()
{
    coroutine<void>::pull_type source{ cooperative };
    try
    {
        source();
    }
    catch (const std::runtime_error &e)
    {
        std::cerr << e.what() << '\n';
    }
}

输出
error

你可能感兴趣的:(C++)