是否可以从其他成员函数在非静态成员函数上启动 boost 线程
就像您可能知道的那样,boost 线程要求作为参数的 fwd 成员函数必须是静态的。如果它不是静态的,有一种绑定方法可以做到这一点,但我更喜欢 Object o; o.startThread() 比 对象o; boost::thread(boost::bind....) 因为它将线程代码保留在类内部(也是异常处理)。 例如,可以将其重写为工作:
class sayHello
{
string name;
public:
sayHello(string name_):name(name_)
{
}
void repeatHello()
{
while (true)
{
boost::this_thread::sleep(posix_time::seconds(3));
cout<<"Hello "<<name<<endl;
}
}
void infiniteRun()
{
boost::thread thr(repeatHello);//broken line
}
};
PS 对于那些徘徊什么是“绑定方式”的人来说,AFAIK 是这样的:
sayHello sh("world");
boost::thread thr(boost::bind(&sayHello::repeatHello,&sh));
like you probably know boost thread requires that memeber function that is fwd as argument must be static. There is a bind way to do it if it is not static, but I prefer the Object o; o.startThread() than
Object o;
boost::thread(boost::bind....) because it keeps the thread code inside the class(also exception handling).
So for example can this be rewritten to work:
class sayHello
{
string name;
public:
sayHello(string name_):name(name_)
{
}
void repeatHello()
{
while (true)
{
boost::this_thread::sleep(posix_time::seconds(3));
cout<<"Hello "<<name<<endl;
}
}
void infiniteRun()
{
boost::thread thr(repeatHello);//broken line
}
};
P.S. for people wandering what is the "bind way" AFAIK it is this:
sayHello sh("world");
boost::thread thr(boost::bind(&sayHello::repeatHello,&sh));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的......
尽管这样做充满了内存泄漏和访问冲突的危险。在处理线程时,我强烈建议使用智能指针来保持线程正确运行。
Yes...
Although doing it that way fraught with danger of memory leaks and access violations. When dealing with threads, I would highly recommend using smart pointers to keep things alive correctly.