【发布时间】:2011-07-26 14:11:31
【问题描述】:
有谁知道在 C++ 中实现 ThreadLocal 的最佳方法,我们可以在必要时设置和获取传递的值。
我在 wikipedia 上阅读了有关 ThraLocal 的信息,它说;
C++0x 引入了 thread_local 关键字。除此之外,各种 C++ 编译器实现提供了声明线程本地的特定方法 变量:
有谁知道这个的 gcc 声明以及它的用法?
【问题讨论】:
有谁知道在 C++ 中实现 ThreadLocal 的最佳方法,我们可以在必要时设置和获取传递的值。
我在 wikipedia 上阅读了有关 ThraLocal 的信息,它说;
C++0x 引入了 thread_local 关键字。除此之外,各种 C++ 编译器实现提供了声明线程本地的特定方法 变量:
有谁知道这个的 gcc 声明以及它的用法?
【问题讨论】:
这通常是您的操作系统使用的任何线程库的一部分。在 Linux 中,线程本地存储由 pthread_key_create、pthread_get_specific 和 pthread_set_specific 函数处理。大多数线程库将封装这一点,并提供 C++ 接口。在 Boost 中,它是 thread_specific_ptr...
【讨论】:
使用 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_create 和 pthread_[sg]et_specific 来访问您自己管理的线程本地数据,在 Windows 上,您可以使用 TlsAlloc 和 Tls[GS]etValue 来访问相同的目的。
一些库为这些提供了包装器,允许使用带有构造函数和析构函数的类型。例如,boost 提供了boost::thread_specific_ptr,它允许您存储每个线程本地的动态分配对象,而我的just::thread 库提供了一个JSS_THREAD_LOCAL 宏,它非常模仿C+ 中thread_local 关键字的行为+0x。
例如使用提升:
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
或者只使用::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
【讨论】:
VC10 有一个名为 combinable 的新类,它为您提供相同的功能,但具有更大的灵活性。
【讨论】:
在 MSVC 中,它被称为 __declspec(thread) 而不是 thread_local。
见http://msdn.microsoft.com/en-us/library/9w1sdazb(v=vs.80).aspx
【讨论】: