Published on

OpenMP 2.0 Leaks Thread Handles

Authors

While developing software with Visual C++ 2008 and OpenMP 2.0, I noticed in Task Manager that the number of threads kept increasing.

Because the program also used Boost.Thread, at first I suspected things like forgetting to join, but in the end it turned out to be an OpenMP bug. If you perform OpenMP parallelization inside a thread, thread handles leak. The following program reproduces the leak.

#include <boost/thread.hpp>

#include <omp.h>

void CalcThread()
{
  double sum = 0.0;
#pragma omp parallel for reduction(+:sum)
  for (int i = 0; i < 1000000000; i++) {
    sum += i;
  }
}

int main()
{
  while (true) {
    boost::thread calc(CalcThread);
    calc.join();
  }

  return 0;
}

It seems that you can avoid the issue by explicitly setting the number of threads inside the loop.

void CalcThread()
{
  double sum = 0.0;
#ifdef _OPENMP
  int num_threads = boost::thread::hardware_concurrency();
  omp_set_num_threads(num_threads - 1);
  omp_set_dynamic(num_threads);
#endif
#pragma omp parallel for reduction(+:sum)
  for (int i = 0; i < 100000000000; i++) {
    sum += i;
  }
}

Reference

http://social.msdn.microsoft.com/Forums/en-US/570e3c2a-b53c-4626-8f79-70f57fec4a97/does-openmp-when-used-in-threads-leak-thread-handles-and-memory