jackscorrow
jackscorrow

Reputation: 702

thread_local variables initialization

I know this is a very basic question but I wasn't able to find a simple answer.

I'm writing a program in which I need some variables to be thread_local. From my understanding this means that those variables are "like global variables" but each thread will have its own copy.

I've put these variables in a dedicated namespace called utils inside a header file called Utilities.hpp in this way:

// Utilities.hpp
namespace utils {
    extern thread_local int var1;
    extern thread_local int var2;
    extern thread_local std::vector<double> vect1;
}

I've used the extern keyword in order to avoid multiple declaration. Anyway when I try to initialize these variables in the .cpp file inside the same namespace like this:

// Utilities.cpp
namespace utils {
    int var1;
    int var2;
    std::vector<double> vect1;
}

I get this error:

Non-thread-local declaration of 'var1' follows thread-local declaration

And the same for every other variable var2 and vect1.

I've tried to initialize them as a normal static variable of a class at the beginning of my program in the main.cpp file like this:

int utils::var1;
int utils::var2;
std::vector<double> utils::vect1;

int main(int argc, const char * argv[]) {

    return 0;
}

but the error I get is always the same.

I don't understand how to initialize this kind of variables, what am I doing wrong?

Upvotes: 3

Views: 4278

Answers (1)

G.M.
G.M.

Reputation: 12879

As per the comments...

The declarations and definitions must match. Hence the thread_local storage qualifier needs to be in both. So you need...

// Utilities.hpp
namespace utils {
  extern thread_local int var1;
  extern thread_local int var2;
  extern thread_local std::vector<double> vect1;
}

and...

// main.cpp
thread_local int utils::var1;
thread_local int utils::var2;
thread_local std::vector<double> utils::vect1;

Upvotes: 6

Related Questions