[C++] how to start thread to run a member function with argument using boost thread?
Within an object, from one member function, I need to start a new thread to run another member function with argument.
I use boost::thread library to start the thread, however, it only accepts a functor with no argument and void as return value. I tried to use boost::bind to work around this as following:
scrap.h:
class X
{
X() {}
virtual ~X();
void run1st();
void run2nd(int i);
};
scrap.cpp:
#include "scrap.h"
#include <boost/bind.hpp>
#include <boost/thread.hpp>
void X::run1st () {
int i = 0;
boost::thread run_run2nd((boost::bind(&X::run2nd, this, _1))(i));
return;
}
void X::run2nd (int i) {
int j;
j = i;
return;
}
When I compile, I got following error:
g++ -O0 -g3 -Wall -I/usr/include -c scrap.cpp
scrap.cpp: In member function ‘void X::run1st()’:
scrap.cpp:8: error: invalid use of void expression
make: *** [scrap.o] Error 1
However, if 'run2nd' has no argument, it works fine with following:
boost::thread run_run2nd(boost::bind(&X::run2nd, this));
I searched the web, it seems that I need a so called function adapter to make this work. But it's not clear how to do that with a class member function. I tried a few times, no luck.
Help is much appreciated.
You're on the right track, but I'm pretty sure (boost::bind(&X::run2nd, this, _1))(i) is essentially run2nd(i) (a void expression). Try boost::bind(&X::run2nd,this,i) or something along those lines to adapt the function.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement