1

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)

user7431005
  • 3,899
  • 4
  • 22
  • 49
  • In my humble opinion, if you want to abstract the parallel part of your program with OpenMP, you should avoid using TLS. Shouldn't be easier to declare the vector as private? Do you really need to privatize it? You may only need to ensure that the access to the vector elements is thread safe (i.e. do not modify vector's number of elements). The information you provide about the parallel loop isn't enough to help you. Try to provide a [minimal, complete and verifiable](https://stackoverflow.com/help/mcve) example to ensure that we understand the problem you want to solve. – Jorge Bellon Sep 04 '17 at 13:01
  • Also, see [OpenMP and reduction on std::vector](https://stackoverflow.com/a/43169193/5809597) – Jorge Bellon Sep 04 '17 at 13:06

1 Answers1

1

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.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243