gpt4 book ai didi

c++ - C++ 11 thread_local变量是否自动静态?

转载 作者:IT老高 更新时间:2023-10-28 12:10:58 25 4
gpt4 key购买 nike

这两个代码段有区别吗:

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 vector V(用于保存一些中间值,每次进入函数时它都会被清除)和一个单线程程序。我想把程序变成一个多线程的程序,所以我必须以某种方式摆脱这个静态修饰符。我的想法是把每一个静态都变成thread_local,而不用担心别的?这种方法会适得其反吗?

最佳答案

根据 C++ 标准

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 变量相同。

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

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

关于c++ - C++ 11 thread_local变量是否自动静态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22794382/

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