C ++ 11 thread_local变量是否自动静态? [英] Are C++11 thread_local variables automatically static?

查看:567
本文介绍了C ++ 11 thread_local变量是否自动静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个代码段之间有区别:

Is there a difference between these two code segments:

void f() {
    thread_local vector<int> V;
    V.clear();
    ... // use V as a temporary variable
}

void f() {
    static thread_local vector<int> V;
    V.clear();
    ... // use V as a temporary variable
}

:原来我有一个STATIC矢量V(用于保存一些中间值,它每次我输入函数时都被清除)和一个单线程程序。我想把程序变成一个多线程的,所以不知何故,我必须摆脱这个静态修饰符。我的想法是把每个静态变成thread_local,不担心别的什么?

Backstory: originally I had a STATIC vector V (for holding some intermediate values, it gets cleared every time I enter the function) and a single-threaded program. I want to turn the program into a multithreading one, so somehow I have to get rid of this static modifier. My idea is to turn every static into thread_local and not worry about anything else? Can this approach backfire?

推荐答案

当thread_local应用于块范围的变量时,
storage-class-specifier static 被隐含,如果它没有出现

When thread_local is applied to a variable of block scope the storage-class-specifier static is implied if it does not appear explicitly

这意味着这个定义

void f() {
    thread_local vector<int> V;
    V.clear();
    ... // use V as a temporary variable
}

等价于

void f() {
    static thread_local vector<int> V;
    V.clear();
    ... // use V as a temporary variable
}

,一个静态变量与thread_local变量相同。

However, a static variable is not the same as a thread_local variable.


1使用thread_local关键字声明的所有变量有线程
存储持续时间。这些实体的存储将持续用于创建它们的线程的
持续时间。每个线程有一个不同的
对象或引用,并且使用的声明名称指向
与当前线程相关联的实体

1 All variables declared with the thread_local keyword have thread storage duration. The storage for these entities shall last for the duration of the thread in which they are created. There is a distinct object or reference per thread, and use of the declared name refers to the entity associated with the current thread

为了区分这些变量,标准引入了一个新术语 线程存储持续时间 以及静态存储持续时间。

To distinguish these variables the standard introduces a new term thread storage duration along with static storage duration.

这篇关于C ++ 11 thread_local变量是否自动静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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