Boost coroutine running on a separate thread?

241 Views Asked by At

I'm using boost::coroutines2::coroutine to create a simple resumable generator pattern - mainly out of convenience in order to avoid the need of managing generator state myself. I'm essentially treating the get_gen function as a factory for multiple resumable generators.

#include <iostream>
#include <boost/coroutine2/all.hpp>
#include <boost/bind.hpp>


class Generator{
public:
    // constructor
    Generator(int size):size(size){}

    // destructor
    ~Generator(){}

    // return a generator that runs the work loop
    boost::coroutines2::coroutine<int>::pull_type get_gen(int mult){
        boost::coroutines2::coroutine<int>::pull_type out(boost::bind(&Generator::work, this, _1, mult));
        return out;
    }

    // the work loop (should run on a separate thread per generator)
    void work(typename boost::coroutines2::coroutine<int>::push_type& yield , int mult){
        for(int i = 0; i< size; i++){
            yield(i*mult);
        }
    }
private:
    int size;
};


using namespace std;
int main()
{
    // debug
    Generator generator_factory(10);
    boost::coroutines2::coroutine<int>::pull_type gen = generator_factory.get_gen(3);
    for(auto gen_output : gen){
        std::cout<<gen_output<<std::endl;
    }
    std::cout<<"done"<<std::endl;
}

Now, I'd like to have the generator method actually execute on a different physical thread - taking advantage of multicore. Ideally, I'd like to be able to ask for multiple generators and know that they all execute on there own thread. How can I achieve this?

0

There are 0 best solutions below