实现C ++ ThreadLocal

时间:2011-07-26 14:11:31

标签: c++ c++11

有人知道在C ++中实现ThreadLocal的最佳方法,我们可以根据需要设置和获取值。

我正在维基百科上阅读有关ThreaLocal的文章,它说道;

  

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

有人知道这个gcc声明,也许是它的用法吗?

4 个答案:

答案 0 :(得分:3)

这通常是您的操作系统使用的线程库的一部分。在Linux中,线程本地存储由pthread_key_createpthread_get_specificpthread_set_specific函数处理。大多数线程库都会封装它,并提供C ++接口。在Boost中,它是thread_specific_ptr ...

答案 1 :(得分:3)

使用gcc,您可以使用__thread来声明线程局部变量。但是,这仅限于具有常量初始化程序的POD类型,并不一定适用于所有平台(尽管它在Linux和Windows上均可用)。您可以将它用作变量声明的一部分,就像使用thread_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_key_createpthread_[sg]et_specific访问自己管理的线程本地数据,在Windows上,您可以使用TlsAllocTls[GS]etValue同样的结局。

某些库为这些提供了包装器,允许使用带有构造函数和析构函数的类型。例如,boost提供boost::thread_specific_ptr,它允许您存储每个线程本地的动态分配对象,我的just::thread库提供了一个JSS_THREAD_LOCAL宏,它近似模仿{的行为来自C ++ 0x的{1}}关键字。

e.g。使用boost:

thread_local

或使用just :: thread:

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

答案 2 :(得分:2)

VC10有一个名为combinable的新类,它可以提供更多灵活性。

答案 3 :(得分:1)

在MSVC中,它被称为__declspec(thread),而不是thread_local

请参阅http://msdn.microsoft.com/en-us/library/9w1sdazb(v=vs.80).aspx