Sign in to follow this  
wld

[C++] how to start thread to run a member function with argument using boost thread?

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this