如何定义线程局部的局部静态变量
How to define thread-local local static variables?
如何定义不同线程之间不共享的局部静态变量(在函数调用之间保持其值)?
我正在寻找C和c++的答案
在Windows上使用Windows API: TlsAlloc()/TlsSetValue()/TlsGetValue()
在Windows上使用编译器:use _declspec(thread)
在Linux(其他POSIX??): get_thread_area()和相关
在你的函数中使用static和__thread。
的例子:
int test(void)
{
static __thread a;
return a++;
}
当前的C标准没有线程或类似的模型,因此您无法在那里得到答案。
POSIX预见的实用程序是pthread_[gs]etspecific
。
下一个版本的C标准增加了线程,并有了线程本地存储的概念。
如果您可以访问c++ 11,您也可以使用c++ 11线程本地存储。
您可以将自己的线程特定的本地存储设置为每个线程ID的单个存储。像这样:
struct ThreadLocalStorage
{
ThreadLocalStorage()
{
// initialization here
}
int my_static_variable_1;
// more variables
};
class StorageManager
{
std::map<int, ThreadLocalStorage *> m_storages;
~StorageManager()
{ // storage cleanup
std::map<int, ThreadLocalStorage *>::iterator it;
for(it = m_storages.begin(); it != m_storages.end(); ++it)
delete it->second;
}
ThreadLocalStorage * getStorage()
{
int thread_id = GetThreadId();
if(m_storages.find(thread_id) == m_storages.end())
{
m_storages[thread_id] = new ThreadLocalStorage;
}
return m_storages[thread_id];
}
public:
static ThreadLocalStorage * threadLocalStorage()
{
static StorageManager instance;
return instance.getStorage();
}
};
GetThreadId ();是特定于平台的函数,用于确定调用者的线程id。像这样:
int GetThreadId()
{
int id;
#ifdef linux
id = (int)gettid();
#else // windows
id = (int)GetCurrentThreadId();
#endif
return id;
}
现在,在一个线程函数中,你可以使用它的本地存储:
void threadFunction(void*)
{
StorageManager::threadLocalStorage()->my_static_variable_1 = 5; //every thread will have
// his own instance of local storage.
}
相关文章:
- 函数局部静态变量:从性能角度来看的优点/缺点
- 关于读取有效 c++ 第 4 项(将非局部静态变量替换为局部静态变量)的问题
- 有什么需要,局部静态变量在编译时分配内存?
- 具有局部静态变量的单例构造函数
- 删除父类时,方法局部静态变量会发生什么情况
- lambda 如何捕获局部静态变量?
- 局部静态变量的初始化多个功能调用
- 如果仅在 lambda 中使用,则不会在发布版本中初始化局部静态变量
- 有没有更好的方法可以使此代码线程安全?线程局部静态似乎是一个生硬的工具
- 使用局部静态std :: ARNE_FLAG和局部静态指针对静态变量的线程安全初始化
- memcpy局部静态变量时出现分段错误
- 使用局部静态变量调用函数
- 在泛型lambda表达式的所有实例化之间共享的局部静态变量
- 要创建持久变量,最好是使用局部静态变量还是全局变量
- 如何在 C++03 中实现线程安全的局部静态变量
- 将成员函数绑定到局部静态变量
- 可能需要引用不同变量的局部静态常量变量
- 如何利用dwarf确定非成员函数中的局部静态变量
- 在VS2015中c++局部静态变量初始化线程安全吗?
- 不持有锁的局部静态初始化避免了c++ 11中可能出现的死锁