user7431005
user7431005

Reputation: 4539

static variable thread_local with open_MP

I tried to use open_MP and use omp prallel for, but I ran into a problem.

I use a lot of different static class members like

class A {
public:
    static std::vector<double> v;
}

which I initialize with an empty vector in my .cpp file.

After some time I make some calculations and finally fill the vector v with my initial values:

A::v = {1,2,3};

after some time I have a big for loop which could (but must not) change the value of v again.

Now I tried to use open_MP to speed things up:

#pragma omp parallel for
for (int i = 0; i < nsched; ++i) {
    ...
}

because I want each loop to have its own instance of the static vector I simply tried to make it thread_local.

class A {
public:
    static thread_local std::vector<double> v;
}

My problem is now, as soon as I get into the parallel for loop my vector v is no longer {1,2,3}, it is simply empty.

How can I change this? I assume that at the beginning v is thread local for the "main-thread" and the newly created "child-threads" don't get the Information about v. Is there a way to easily solve this problem? Or do I need to initialize v for each thread? (this would not be great, because the initialization takes quite some time and it is unlikely (but possible) that I need to change the parameters in each for loop)

Upvotes: 1

Views: 713

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

If you write an initialisation

thread_local std::vector<double> A::v {1,2,3};

you will get a copy of v containing {1,2,3} in all threads. But if you write an assignment

A::v = {1,2,3};

you will not. A::v will be initialised afresh for each thread and not copied from any other thread.

If you need a thread local copy of an array initialised to some set of values, you will have to make sure the action (either initialisation or assignment) that puts the values there is performed in each thread.

Upvotes: 1

Related Questions