这两个代码段之间是否存在差异:
void f() {
thread_local vector<int> V;
V.clear();
... // use V as a temporary variable
}
Run Code Online (Sandbox Code Playgroud)
和
void f() {
static thread_local vector<int> V;
V.clear();
... // use V as a temporary variable
}
Run Code Online (Sandbox Code Playgroud)
Backstory:最初我有一个STATIC向量V(用于保存一些中间值,每次进入函数时都会被清除)和一个单线程程序.我想把程序变成多线程程序,所以我不得不摆脱这个静态修饰符.我的想法是将每个静态转换为thread_local并且不担心其他任何事情?这可能会适得其反吗?
现在C++正在添加thread_local存储作为语言功能,我想知道一些事情:
thead_local可能的成本是多少?
thread_local都必须为每个创建的线程提供特定于线程的存储空间.例如:
#include <thread>
thread_local int n = 1;
void f()
{
++n; // is n initialized here for each thread or prior to entering f()?
}
int main()
{
std::thread ta(f);
std::thread tb(f);
ta.join();
tb.join();
}
Run Code Online (Sandbox Code Playgroud)
它仍然是不完全清楚,从这里为n初始化时。
我知道这是一个非常基本的问题,但我找不到简单的答案。
我正在编写一个程序,其中需要一些变量thread_local。根据我的理解,这意味着这些变量“像全局变量”,但每个线程都有自己的副本。
我将这些变量放在一个专用的命名空间中,utils在头文件中调用Utilities.hpp,以这种方式调用:
// Utilities.hpp
namespace utils {
extern thread_local int var1;
extern thread_local int var2;
extern thread_local std::vector<double> vect1;
}
Run Code Online (Sandbox Code Playgroud)
我使用extern关键字是为了避免多重声明。无论如何,当我尝试像这样初始化.cpp文件中的这些变量时namespace:
// Utilities.cpp
namespace utils {
int var1;
int var2;
std::vector<double> vect1;
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
Non-thread-local declaration of 'var1' follows thread-local declaration
Run Code Online (Sandbox Code Playgroud)
var2对于其他所有变量也是如此vect1。
我尝试在文件中的程序开头将它们初始化为类的普通静态变量,main.cpp如下所示:
int utils::var1;
int utils::var2;
std::vector<double> utils::vect1;
int main(int argc, const char * argv[]) {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但我得到的错误总是相同的。
我不明白如何初始化这种变量,我做错了什么?