简体   繁体   中英

Is a boost::thread automatically removed from a boost::thread_group when it terminates?

( This question , though similar, didn't really answer my question.)

I've had problems with my own "thread group" implementation , and being no closer to solving or even identifying the issue, I'm looking into just using boost::thread_grp .

Now, from what documentation I can find on the subject 1 , I've always believed that thread objects — no matter the duration of their actual work — remain alive and a part of a thread group until the thread group is destroyed.

However, a cursory test seems to indicate that boost::thread_group::size() decreases on its own as threads do their work and terminate. That would imply that the thread objects themselves are being cleaned up for me, too.

Is this true? Can I rely on it?

#include <cassert>
#include <unistd.h>         // for sleep()
#include <boost/thread.hpp>

boost::mutex m;
unsigned int count = 0;

void func() {
   boost::mutex::scoped_lock l(m);
   count++;
}

int main()
{
   boost::thread_group grp;
   for (size_t i = 0; i < 300; i++)
      grp.create_thread(func());

   sleep(10);

   assert(count == 300);
   assert(grp.size() == 0);  // passes, in my tests

   // ^ Can I rely on that?
   //   Do I really have no thread objects eating up
   //     memory, at this point?

   grp.join_all();
   // ^ Then I guess this is doing nothing, in this case...
}

If it is, then my entire original has_threads implementation was just a broken clone and I've wasted my time. :)

And, yes, assert was a really poor choice for this snippet, since I guess it could lead to any unlikely-outstanding threads from butchering the memory under what used to be count ? Anyway, never mind that.


1 - I'm stuck on Boost 1.40, but the documentation on the matter seems to be the same for more recent versions.


Update

This thread is an example of where people are saying the opposite of what my testing has shown. It does also provide a decent solution if that's the case, though; it's nice that thread_group is totally thread-safe (though I'm not convinced that that shared_ptr::get() is thread-safe; what if the thread ends before the shared_ptr::reset has finished?). Do I need to employ this solution?

No, I misinterpreted the results of my test by not abstracting away the task scheduler that creates threads for me. In short, I was checking size() on the wrong boost::thread_group .

In fact, boost::thread_group::size() doesn't go down on its own as threads terminate, so I'll be using an adapted version of the solution provided in the forum post I linked to in the question update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM