[英]use of MultiThread with boost in VC++
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. 我是Boost,C ++和线程技术的新手,我正在尝试通过Boost库使用线程,但是我无法通过对象访问函数。
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. 调用boost::thread thread_a(obj.print_a)
时出现错误boost::thread thread_a(obj.print_a)
是一个pointer to a bound function may only be called to use this function
的pointer to a bound function may only be called to use this function
并且与thread_b相同,但是对于thread_x和thread_y来说,它可以正常工作。 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 除非有我不知道的新语法,否则您无法将obj.print_a
传递为必须执行的“可运行”操作
boost::bind( &myclass::print_a, &obj );
or std::bind
if your version supports it. 或std::bind
如果您的版本支持)。
As it happens boost::thread
has a multi-parameter version that does the bind for you. 碰巧boost::thread
具有多参数版本,可以为您执行绑定。 Thus when you create the thread 因此,当您创建线程时
boost::thread thread_a( &myclass::print_a, &obj );
In C++11 you can also use lambdas 在C ++ 11中,您也可以使用lambda
[&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. 或者,如果看起来太凌乱,则分配lambda(您当然可以使用auto作为其类型),然后将其传递到单独的行中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.