gkpln3
gkpln3

Reputation: 1499

OpenMP treat all static variables as threadprivate by default

I have a C function that I need to run on multiple inputs in parallel.

I am trying to use OpenMP to do so, the issue is, that the function I am using is using some internal static variables for its own internal calculations.

When trying to run multiple instances of this function in parallel, the program crashes due to the fact that multiple threads are accessing the same memory region.

This can be solved by defining each and every static variable as "threadprivate", but since I have many internal variables, this is a bit overkill.

Is there any way to make OpenMP treat all variables as "threadprivate" by default?

Upvotes: 4

Views: 846

Answers (1)

Zulan
Zulan

Reputation: 22670

There is no such possibility.

No you could maybe attempt some adventurous #define static, but I would strongly advise against that.

The thing is. A function using static isn't suddenly thread-safe if you replace all of them with thread-locals. Consider:

int unique_number() {
    static i = 0;
    return i++; // surely this is unique!
}

It gets worse if you have functions capturing state across invocations such as the infamous strtok:

my_threadlocal_strtok(str, ...);
#pragma omp parallel for
for () {
    my_threadlocal_strtok(NULL, ...); //
}

You have to consider the "lifecycle" of this static - or now threadlocal - state.

Defining a bunch of threadlocal variables that used to be static makes it much harder to reason about parallel code and is likely going to introduce subtle bugs. The same goes for global variables, by the way, which also make parallelization much harder.

At the end of the day, don't abuse static to store state across invocations. Instead use explicit handles for the state. If you wish to transparently cache data, and things get out of hand with static. You can consider abstracting the state of the cache with explicit initialization/access functions which are then easier to use in a thread-safe / thread-local manner. This is much easier in C++ than it is in C.

Upvotes: 1

Related Questions