C++ 如何定义线程局部静态变量?
如何定义不同线程之间不共享的局部静态变量(在函数调用之间保持其值)C++ 如何定义线程局部静态变量?,c++,c,multithreading,static,thread-safety,C++,C,Multithreading,Static,Thread Safety,如何定义不同线程之间不共享的局部静态变量(在函数调用之间保持其值) 我在C和C++中寻找答案当前的C标准没有线程或类似的模型,因此您无法得到答案 POSIX为此预见的实用程序是pthread_gs]etspecific C标准的下一个版本添加了线程,并具有线程本地存储的概念。在Windows上使用Windows API:/TlsSetValue()/TlsGetValue() 在Windows上使用编译器内部:使用 在Linux(其他POSIX???):和相关的上,只需在函数中使用静态和__线程
我在C和C++中寻找答案当前的C标准没有线程或类似的模型,因此您无法得到答案 POSIX为此预见的实用程序是
pthread_gs]etspecific
C标准的下一个版本添加了线程,并具有线程本地存储的概念。在Windows上使用Windows API:/TlsSetValue()/TlsGetValue() 在Windows上使用编译器内部:使用
在Linux(其他POSIX???):和相关的上,只需在函数中使用静态和__线程即可 例如:
int test(void)
{
static __thread a;
return a++;
}
您可以将自己的特定于线程的本地存储设置为每个线程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();
}
};
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++11,也可以使用C++11线程本地存储添加。您使用的是什么操作系统?TLS在unixen和windows之间不可移植。C++11引入了另一个名为的存储持续时间。试着使用它。@Nawaz:C++11和C11。在C11中,它是
\u-Thread\u-local
,除非您还包括
(这将\define
添加到Thread\u-local
,就像C99和更高版本一样)。在阅读了MSDN之后,Tls函数正是我想要的。@Ali:不,它是GCC和其他一些编译器提供的扩展。在MSVC上,我认为您可以使用\uuu declspec(thread)
来代替。它可以简单地定义为windows上的declspec(线程)。它不适用于macOS上的gcc或clang,因为它需要操作系统支持。您还需要同步(如读/写互斥)来保护m_存储
不被多个线程访问。不仅m_存储,还包括std::map和本地“静态StorageManager实例;不是线程安全的。在本机代码中实现高效的单例不是一件容易的事情,请参阅Scott Meyers和Andrei Alexandrescu的“C++和双重检查锁定的危险”。