when to detach or join a boost thread?

泪湿孤枕 提交于 2019-12-09 16:38:54

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9527427/when-to-detach-or-join-a-boost-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!