Using boost::asio::post for a function that takes in parameters
Asked Answered
L

1

6

I'm new to using boost, and threadpools. I want to pass a function to a threadpool that takes a variable as a parameter. In this simple example I'm just passing in an integer. My understanding is post is going to call an available thread in the thread pool to do something. The code compiles if I set up printProduct to not take in any variables, but that's not what I'm eventually trying to do.

References to relevant documentation would be very helpful (I haven't successfully found much discussion of boost::asio::post), as well as advice on how to solve the problem. Thanks!

#include <cstdlib> 
#include <iostream>
#include <pthread.h>
#include <boost/version.hpp>    // version is 1.72
#include <boost/asio.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/thread_pool.hpp>
#include <boost/asio/thread_pool.hpp>
#include <boost/asio/post.hpp>
#include <boost/lockfree/queue.hpp>

using namespace std;

int printProduct(int endval){
    // int endval = 1000000;
    int prod = 1;
    for (int i=0;i<endval;i++){
        prod = prod * i;
    }
    return prod;
}


int main() {

    boost::asio::thread_pool tp(8);

    for (int i =0; i<200; i++){
        // issue is how to pass the parameter into post
        boost::asio::post(tp, printProduct,i);
        // boost::asio::post(tp, printProduct(i));
    }
}
Lysander answered 5/3, 2020 at 18:41 Comment(1)
I would just use lambdas instead link to boost docsBurletta
R
21

boost::asio::post takes any callable object. Requirements for such object you can find here.

There are many ways to achive what you want:

[1] lambda expressions

boost::asio::post(tp, [i]{ printProduct(i); });

[2] bind

boost::asio::post(tp, std::bind(printProduct,i));

[3] custom functor class

struct Wrapper {
    int i;

    Wrapper(int i) : i(i) {}

    void operator()() {
        printProduct(i);
    }
};

boost::asio::post(Wrapper{i});
Roderich answered 5/3, 2020 at 18:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.