thread_local variables initialization

南笙酒味 提交于 2020-01-05 08:28:19

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/43424789/thread-local-variables-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!