Search code examples
c++multithreadingopenmp

OpenMP thread initialization and de-initialization before doing work


I am using an API that needs to be started and stopped for every thread in which it is used. So if I want to do something with the API in a specific thread I have to call api_start() (and api_stop() afterwards).

Now I have a very trivial problem I can solve in parallel which I want to try with OpenMP. Consider the problem is looking like this:

#pragma omp parallel for num_threads(NUM_THREADS), default(none)
for (auto i = 0; i < count; i++)
{
    api_process(i);
}

This will not work because the worker threads of OpenMP did not call api_start() or api_stop() so a working solution would be:

#pragma omp parallel for num_threads(NUM_THREADS), default(none)
for (auto i = 0; i < count; i++)
{
    api_start();
    api_process(i);
    api_stop();
}

But this solution will bring up overhead because now a thread calls api_start() and api_stop() multiple times (if NUM_THREADS < count).

So my question is: Is there a way in OpenMP to define a function to call for every created thread once on startup and once on deletion?

Thanks in advance!


Solution

  • You can call the functions manually at the beginning/end of the first/last iteration, respectively, or use something as std::call_once. However, this would add some overhead into each iteration (branching).

    EDIT: Actually, this wouldn't work since only a single thread would call those functions. You would need to define some thread-local flags and check them in iterations. Same downside.

    A much better alternative would be simply to split parallel and for OpenMP code blocks:

    #pragma omp parallel
    {
      api_start();
    
      #pragma omp for
      for (auto i = 0; i < count; i++)
      {
        api_process(i);
      }
    
      api_stop();
    }