5
votes

When threads are added to boost::thread_group like:

boost::thread_group my_threads;
boost::thread *t = new boost::thread( &someFunc );
my_threads.add_thread(th);

all the created boost::thread objects are deleted only when my_threads object is out of scope. But my program main thread spawns a lot of threads while execution. So if about 50 threads are already done, about 1,5Gb of memory is used by program and this memory is freed only on main process termination.

The question is: How to delete these boost::thread object when thread function is finished ?!

1
I believe this question is similar: stackoverflow.com/questions/3970818/… - Naveen
@Naveen, I do really need a wrapper that can interrupt all pooled children threads when main thread asks for it. In question you linked they recommend just create a thread and detach boost::thread object from it. - Didar_Uranov

1 Answers

6
votes

You could do sth like this, but mind synchronization (it is better to use shared pointer to boost::thread_group instead of reference, unless you are sure, that thread group will live long enough):

void someFunc(..., boost::thread_group & thg, boost::thread * thisTh)
{
  // do sth

  thg.remove_thread(thisThr);
  delete thisTh; // we coud do this as thread of execution and boost::thread object are quite independent
}

void run()
{
  boost::thread_group my_threads;
  boost::thread *t = new boost::thread(); // invalid handle, but we need some memory placeholder, so we could pass it to someFunc
  *t = boot::thread(
    boost::bind(&someFunc, boost::ref(my_threads), t)
  );
  my_threads.add_thread(t);
  // do not call join
}

You could also check at_thread_exit() function.

Anyway, boost::thread objects should not weight 30 MB.