May 8, 2017 at 3:21am UTC
I am studying thread-pool with asynchronous I/O. Now, I tried to bind a function with return value. However, it failed. Can anyone please help (the code which starts with "ioService.post")?
Thank you very much.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include <vector>
#include <ppl.h>
#include <iostream>
#include <chrono>
#include <boost/asio/io_service.hpp>
#include <boost/thread/thread.hpp>
#include <boost/phoenix/phoenix.hpp>
#include <boost/function.hpp>
using namespace std;
typedef vector<double > Vector;
typedef vector<Vector> Matrix;
class myClass {
private :
int num;
Matrix a;
Vector z;
public :
myClass(int n) :
num(n), a(num, Vector(2)) {}
Vector subFun(int n) {
Vector b(2, 0);
b[0] = n;
b[1] = n+num;
//body: to be implemented
return b;
}
void mainFun() {
Matrix z;
Vector w;
boost::asio::io_service ioService;
boost::thread_group threadpool;
boost::asio::io_service::work work(ioService);
for (int i = 0; i < std::thread::hardware_concurrency(); i++) {
threadpool.create_thread(
boost::bind(&boost::asio::io_service::run, &ioService)
);
}
for (int i = 0; i < num; i++) {
ioService.post(boost::phoenix::bind(&myClass::z, this ) =
boost::phoenix::bind(&myClass::subFun, this , i));//OK
ioService.post(boost::phoenix::bind(&myClass::a[i], this ) =
boost::phoenix::bind(&myClass::subFun, this , i));//FAIL
ioService.post(boost::phoenix::bind(w) =
boost::phoenix::bind(&myClass::subFun, this , i));
//local variable w -->FAIL
}
ioService.stop();
threadpool.join_all();
}
Matrix getA() {
return a;
}
};
Last edited on May 8, 2017 at 3:22am UTC
May 8, 2017 at 11:53am UTC
Wrap the function that returns a value in a function that instead takes a reference and assigns the return value to that.
May 8, 2017 at 1:54pm UTC
Sorry, I cannot understand what you mean. Can you please illustrate your idea by code? Thanks.
May 9, 2017 at 4:17pm UTC
Thank you very much.
You use lambda function instead of phoenix bind function. It works. In the capture list, "this" is used because subFun is a member function of myClass, is it right?
May 9, 2017 at 5:10pm UTC
Last edited on May 9, 2017 at 5:10pm UTC