【问题标题】:Is it possible to nest coroutines using Boost.Coroutine?是否可以使用 Boost.Coroutine 嵌套协程?
【发布时间】:2013-09-25 20:49:44
【问题描述】:

我想在已经在协程中时调用协程。可以使用Boost.Coroutine吗?

【问题讨论】:

    标签: c++ boost c++11 coroutine


    【解决方案1】:

    是的,很简单:

    #include <iostream>
    #include <boost/coroutine/coroutine.hpp>
    
    typedef boost::coroutines::coroutine<int()> generator;
    
    void bar(generator::caller_type& yield)
    {
      for (std::size_t i = 100; i < 110; ++i)
        yield(i);
    }
    
    void foo(generator::caller_type& yield)
    {
      for (std::size_t i = 0; i < 10; ++i)
      {
        generator nested_gen(bar);
        while (nested_gen)
        {
          std::cout << "foo: " << nested_gen.get() << std::endl;
          nested_gen();
        }
        yield(i);
      }
    }
    
    int main()
    {
      generator gen(foo);
      while (gen)
      {
        std::cout << "main: " << gen.get() << std::endl;
        gen();
      }
      return 0;
    };
    

    编辑: 使用 Boost >= 1.56

    #include <iostream>
    #include <boost/coroutine/asymmetric_coroutine.hpp>
    
    using generator = typename boost::coroutines::asymmetric_coroutine<std::size_t>::pull_type;
    using yield_type = typename boost::coroutines::asymmetric_coroutine<std::size_t>::push_type;
    
    void bar(yield_type& yield)
    {
      for (std::size_t i = 100; i < 110; ++i)
        yield(i);
    }
    
    void foo(yield_type& yield)
    {
      for (std::size_t i = 0; i < 10; ++i)
      {
        generator nested_gen{bar};
        while (nested_gen)
        {
          std::cout << "foo: " << nested_gen.get() << '\n';
          nested_gen();
        }
        yield(i);
      }
    }
    
    int main()
    {
      generator gen{foo};
      while (gen)
      {
        std::cout << "main: " << gen.get() << '\n';
        gen();
      }
      return 0;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      相关资源
      最近更新 更多