we experience a high memory overhead when reusing threads that use Intel TBB functions. We expected that once a thread has finished a given workload, it would free the respective memory. However, this does not seem to be the case, even if there are long pauses between the execution of work units by a thread.
We prepared an example to show the problem:
int main() {
blocking_queue<size_t> command_input_queue;
tbb::atomic<size_t> count = 1;
//workers
std::vector<std::thread> worker;
for(size_t i = 0; i < 15; i++) {
worker.push_back(std::thread([&command_input_queue, &count](){
while(true)
{
size_t size;
//wait for work..
command_input_queue.wait_and_pop(size);
//do some work with Intel TBB
std::vector<int32_t> result(size);
for(size_t i = 0; i < result.size(); i++) {
result[i] = i % 1000;
}
tbb::parallel_sort(result.begin(), result.end());
size_t local_count = count++;
std::cout << local_count << " work items executed " << std::endl;
}
}));
}
//enqueue work
size_t work_items = 15;
for(size_t i = 0; i < work_items ; i++) {
command_input_queue.push(10 * 1000 * 1000);
}
while(true) {
boost::this_thread::sleep( boost::posix_time::seconds(1) );
if(count > 15) {
break;
}
}
//wait for more commands
std::cout << "Wait" << std::endl;
boost::this_thread::sleep( boost::posix_time::seconds(60) );
//----!During the wait, while no thread is active,
//the process still claims over 500 MB of memory!----
for(size_t i = 0; i < 15; i++) {
command_input_queue.push(1000 * 1000);
}
...
In the example we start 15 worker threads. They wait for tasks and do a tbb::parallel_sort and release all resources after they are done. The problem is after all tasks are processed and all workers wait for new tasks, the process still claims 500MB of memory.
Tools like valgrind's massif didn't show us where the memory is claimed. We linked the program against the libtbb.so. So tbb allocators shouldn't be the problem.
Does anybody know how we can release the memory, while a worker is idle?
malloc_trim(See answer below) it goes down to ~2MB. So it seems to be system dependent. - Robert Seilbeck