[英]use of MultiThread with boost in VC++
我是Boost,C ++和线程技术的新手,我正在尝试通过Boost库使用线程,但是我无法通过对象访问函数。
这是我在做什么:
#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;
}
调用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来说,它可以正常工作。 我想念的是什么,请引导我
谢谢你的问候
除非有我不知道的新语法,否则您无法将obj.print_a
传递为必须执行的“可运行”操作
boost::bind( &myclass::print_a, &obj );
或std::bind
如果您的版本支持)。
碰巧boost::thread
具有多参数版本,可以为您执行绑定。 因此,当您创建线程时
boost::thread thread_a( &myclass::print_a, &obj );
在C ++ 11中,您也可以使用lambda
[&obj]{ obj.print_a(); }
因此在一排
boost::thread thread_a( [&obj]{ obj.print_a(); } );
或者,如果看起来太凌乱,则分配lambda(您当然可以使用auto作为其类型),然后将其传递到单独的行中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.