Processing of exceptions inside parallel sections

Andrey Karpov
Articles: 374



Some time ago I wrote in the blog about some problems (see note "OpenMP and exceptions") occurring when an exception excesses the boundaries of parallel sections. I have also told you that an exception can be generated by new operator and that is must be caught and processed before it leaves the parallel section. The constructions used for this are rather inconvenient and complicated. Not so long ago I was told that in this case the smartest solution is using new operator which does not generate exceptions. That is using of a "nothrow"-variant of new operator which returns NULL in case of failure and allows you to write a simpler OpenMP code.

To get acquainted with new operator which does not generate exceptions see the article "Nothrow new". And here I will give only two examples which demonstrate the idea of the solution very clear.

The code with processing of an exception:

size_t errCount = 0;
#pragma omp parallel for num_threads(4) reduction(+: errCount)
for(int i = 0; i < 4; i++)
{
  try {
    float *ptr = new float[10000];
    // code
    delete [] ptr;
  }
  catch (std::bad_alloc &)
  {
    ++errCount;
  }
}

Simplified code without processing of exceptions:

size_t errCount = 0;
#pragma omp parallel for num_threads(4) reduction(+: errCount)
for(int i = 0; i < 4; i++)
{
  float *ptr = new(std::nothrow) float[10000];
  if (ptr == NULL) {
    ++errCount;
  } else {
    // code
    delete [] ptr;
  }
}


Use PVS-Studio to search for bugs in C, C++, C# and Java

We offer you to check your project code with PVS-Studio. Just one bug found in the project will show you the benefits of the static code analysis methodology better than a dozen of the articles.

goto PVS-Studio;

Andrey Karpov
Articles: 374


Bugs Found

Checked Projects
355
Collected Errors
13 303