[英]How to define thread-local local static variables?
如何定义不在不同线程之间共享的局部静态变量(在函数调用之间保持其值)?
我正在寻找 C 和 C++ 的答案
在 Windows 上使用 Windows API: TlsAlloc() /TlsSetValue()/TlsGetValue()
在 Windows 上使用编译器内在:使用_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();
}
};
获取线程 ID(); 是一个特定于平台的函数,用于确定调用者的线程 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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.