I am new to boost, C++ and threading, I am trying to use thread using boost library, but I am not able to access function through objects.
Here is what I am doing:
#include <iostream>
#include <boost/thread.hpp>
using namespace std;
class myclass
{
int a,b;
public:
void print_a();
void print_b();
};
void myclass::print_a()
{
for(int i=1;i<1000000;++i) cout<<"printing a"<<endl;
}
void myclass::print_b()
{
for(int i=1;i<1000000;++i) cout<<"printing b"<<endl;
}
void print_x()
{
for(int i=1;i<1000000;++i) cout<<"printing x"<<endl;
}
void print_y()
{
for(int i=1;i<1000000;++i) cout<<"printing y"<<endl;
}
int main()
{
myclass obj;
boost::thread thread_a(obj.print_a);
boost::thread thread_b(obj.print_b);
boost::thread thread_x(print_x);
boost::thread thread_y(print_y);
thread_a.join();
thread_b.join();
thread_x.join();
thread_y.join();
return 0;
}
Error when calling boost::thread thread_a(obj.print_a)
is a pointer to a bound function may only be called to use this function
and same with thread_b but for thread_x and thread_y it is working properly. What am I missing, please guide me
Thank You Regards
Unless there is a new syntax I don't know about, you cannot pass obj.print_a
as a "runnable" you have to do
boost::bind( &myclass::print_a, &obj );
or std::bind
if your version supports it.
As it happens boost::thread
has a multi-parameter version that does the bind for you. Thus when you create the thread
boost::thread thread_a( &myclass::print_a, &obj );
In C++11 you can also use lambdas
[&obj]{ obj.print_a(); }
thus in one line
boost::thread thread_a( [&obj]{ obj.print_a(); } );
or if that looks too messy assign the lambda (you can use auto of course as its type) and pass that in a separate line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.