何时分离或加入boost线程? [英] when to detach or join a boost thread?

查看:116
本文介绍了何时分离或加入boost线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,每30秒aprox一次。我需要在一个线程。



我有一个方法,我可以从类外面调用。例如callThreadedMethod(),它创建自己调用最终threadMethod的线程。



这些是MyClass的方法

  void callThreadedMethod(){
mThread = boost :: shared_ptr< boost :: thread>(new boost :: thread(& MyClass :: threadedMethod,this)
}

void threadedMethod(){
//更多代码不在while循环中
}


这是足够调用join ()in the MyClass destructor?



当threadMethod结束时线程是否会自毁?

解决方案

这取决于你想要实现什么。如果你不在乎什么时候或者如果对 threadedMethod 的调用终止或者它们是否抛出,那么你可以只是分离线程,一旦你创建它;每个线程将在方法完成时被销毁。



如果你在乎,那么你需要调用 join 在你创建的每个线程(所以每个线程一次,而不是一次在析构函数)。我怀疑你不会。



你真的需要为每个电话创建一个新的线程吗?线程创建可能很昂贵,所以一个替代方法是使用线程池并提交每个 threadedMethod 调用。然后,池可以具有MyClass 实例的生命周期。但也许这只是每30秒发生一次的东西。


I have a method which is fired once every 30 seconds aprox. that I need to have in a thread.

I have a method that I can call from outside the class. Something like callThreadedMethod() which creates the thread which itself calls the final threadedMethod.

These are methods of MyClass

void callThreadedMethod(){
    mThread = boost::shared_ptr<boost::thread>(new boost::thread(&MyClass::threadedMethod, this));
}

void threadedMethod(){
    //more code NOT inside a while loop
}

So do I have to detach mThread every time the method is called?

Is it enough to call join() in the MyClass destructor?

Does the thread destroys itself when threadedMethod finishes?

解决方案

It depends what you want to achieve. If you don't care when or if the calls to threadedMethod terminate, or whether or not they throw, then you can just detach the thread as soon as you've created it; each thread will be destroyed when the method completes. And you shouldn't store the thread in a member variable.

If you do care then you need to call join on each thread you create (so once per thread, not once in the destructor). I suspect you don't.

Do you really need to create a new thread for each call? Thread creation can be expensive, so an alternative would be to use a thread pool and submit each threadedMethod invocation to that. The pool could then have the lifetime of the MyClass instance. But perhaps that's overkill for something that is only happening once every 30s.

这篇关于何时分离或加入boost线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆