thread_local变量初始化 [英] thread_local variables initialization

查看:278
本文介绍了thread_local变量初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

对于其他所有变量var2vect1都是相同的.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆