C++ 实施C++;线程本地

C++ 实施C++;线程本地,c++,c++11,C++,C++11,我在维基百科上读到关于ThreaLocal的文章,上面说 C++0x引入了thread\u local关键字。除此之外,各种C++ 编译器实现提供了声明线程本地的特定方法 变量: 有人知道这方面的gcc声明以及它的用法吗?这通常是操作系统使用的线程库的一部分。在Linux中,线程本地存储由pthread\u key\u create、pthread\u get\u specific和pthread\u set\u specific函数处理。大多数线程库将封装此,并提供C++接口。在Boost中,

我在维基百科上读到关于ThreaLocal的文章,上面说

C++0x引入了thread\u local关键字。除此之外,各种C++ 编译器实现提供了声明线程本地的特定方法 变量:


有人知道这方面的gcc声明以及它的用法吗?

这通常是操作系统使用的线程库的一部分。在Linux中,线程本地存储由
pthread\u key\u create
pthread\u get\u specific
pthread\u set\u specific
函数处理。大多数线程库将封装此,并提供C++接口。在Boost中,它是特定于线程的ptr,在MSVC中它被称为
\u declspec(thread)
,而不是
线程本地


请参见

VC10有一个新的类,名为,它为您提供了同样的功能,具有更大的灵活性。

对于gcc,您可以使用
\u thread
来声明线程局部变量。但是,这仅限于具有常量初始值设定项的POD类型,并且不一定在所有平台上都可用(尽管它在linux和Windows上都可用)。您可以使用它作为变量声明的一部分,就像使用
thread\u local
一样:

__thread int i=0;
i=6; // modify i for the current thread
int* pi=&i; // take a pointer to the value for the current thread
在POSIX系统上,您可以使用
pthread\u key\u create
pthread\u[sg]et\u specific
访问您自己管理的线程本地数据,在Windows上,您可以使用
TlsAlloc
Tls[GS]etValue
达到相同的目的

有些库为这些类型提供包装,允许使用构造函数和析构函数的类型。例如,boost提供了一个允许您存储每个线程本地的动态分配对象的宏,my library提供了一个与C++0x中的
thread\u local
关键字的行为非常相似的宏

e、 g.使用boost:

boost::thread_specific_ptr<std::string> s;
s.reset(new std::string("hello")); // this value is local to the current thread
*s+=" world"; // modify the value for the current thread
std::string* ps=s.get(); // take a pointer to the value for the current thread
JSS_THREAD_LOCAL(std::string,s,("hello")); // s is initialised to "hello" on each thread
s+=" world"; // value can be used just as any other variable of its type
std::string* ps=&s; // take a pointer to the value for the current thread