Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete boost thread object when thread itself terminates?

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 ?!

like image 210
Didar_Uranov Avatar asked May 21 '12 08:05

Didar_Uranov


1 Answers

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.

like image 169
Greg Avatar answered Oct 30 '22 15:10

Greg