thread_local变量初始化 [英] thread_local variables initialization
问题描述
我知道这是一个非常基本的问题,但我找不到简单的答案.
I know this is a very basic question but I wasn't able to find a simple answer.
我正在编写一个程序,其中需要一些变量作为thread_local
.以我的理解,这意味着这些变量像全局变量",但是每个线程都有自己的副本.
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.
我已通过以下方式将这些变量放在名为Utilities.hpp
的头文件内的名为utils
的专用命名空间中:
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;
}
我使用了extern
关键字以避免重复声明.
无论如何,当我尝试在同一namespace
内的.cpp
文件中初始化这些变量时,像这样:
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;
}
我收到此错误:
Non-thread-local declaration of 'var1' follows thread-local declaration
对于其他所有变量var2
和vect1
都是相同的.
And the same for every other variable var2
and vect1
.
我尝试在main.cpp
文件的程序开头将它们初始化为类的普通静态变量,如下所示:
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?
推荐答案
根据评论...
声明和定义必须匹配.因此,thread_local
存储限定符必须同时存在.所以你需要...
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;
}
和...
// main.cpp
thread_local int utils::var1;
thread_local int utils::var2;
thread_local std::vector<double> utils::vect1;
这篇关于thread_local变量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!