2011-07-26 32 views
4

有谁知道在C++中实现ThreadLocal的最佳方式,我们可以设置并获取当需要时传递的值。实现一个C++ ThreadLocal

我在读wikipedia上的ThreaLocal,它说:

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

做谁知道这个海湾合作委员会的声明,或许它的使用?

回答

3

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

2

VC10有一个名为combinable新的类,它为您提供了同样的事情,有更多的灵活性。

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中关键字thread_local的行为。

例如使用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