gpt4 book ai didi

c++ - thread_local 变量初始化

转载 作者:行者123 更新时间:2023-11-30 05:14:30 30 4
gpt4 key购买 nike

我知道这是一个非常基本的问题,但我找不到简单的答案。

我正在编写一个程序,其中我需要一些变量是 thread_local。根据我的理解,这意味着这些变量“像全局变量”,但每个线程都有自己的拷贝。

我以这种方式将这些变量放在名为 Utilities.hpp 的头文件中名为 utils 的专用命名空间中:

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

我使用了 extern 关键字来避免多重声明。无论如何,当我尝试在同一 namespace 内的 .cpp 文件中初始化这些变量时,如下所示:

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

我收到这个错误:

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

对于所有其他变量 var2vect1 也是如此。

我在 main.cpp 文件中的程序开头尝试将它们初始化为类的普通静态变量,如下所示:

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

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

return 0;
}

但我得到的错误总是一样的。

我不明白如何初始化这种变量,我做错了什么?

最佳答案

根据评论...

声明和定义必须匹配。因此 thread_local 存储限定符需要在两者中。所以你需要...

// 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;

关于c++ - thread_local 变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43424789/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com