template<typename T>
class ThreadLocal
{
public:
ThreadLocal()
{
pthread_key_create(&_pkey, &ThreadLocal::destructor);
(void)sizeof(T);
}
~ThreadLocal()
{
pthread_key_delete(_pkey);
}
T& value()
{
T* thread_value = static_cast<T*>(pthread_getspecific(_pkey));
if (thread_value == NULL) {
T* new_obj = new T();
pthread_setspecific(_pkey, new_obj);
thread_value = new_obj;
}
return *thread_value;
}
template <typename A1>
T& value(A1 arg1) {
T* thread_value = static_cast<T*>(pthread_getspecific(_pkey));
if (!thread_value) {
T* new_obj = new T(arg1);
pthread_setspecific(_pkey, new_obj);
thread_value = new_obj;
}
return *thread_value;
}
ThreadLocal& operator=(const T& v)
{
value() = v;
return *this;
}
operator T() const
{
T* thread_value = static_cast<T*>(pthread_getspecific(_pkey));
return *thread_value;
}
private:
static void destructor(void *x)
{
T* obj = static_cast<T*>(x);
delete obj;
}
private:
pthread_key_t _pkey;
};
TLS thread local storing
最新推荐文章于 2024-03-27 10:45:20 发布
本文介绍了一个使用 C++ 实现的线程局部存储 (TLS) 类。该类允许每个线程拥有自己的变量副本,从而避免了多线程环境中的数据竞争问题。文中详细展示了 TLS 的构造、析构过程及如何获取线程特有值。
5940

被折叠的 条评论
为什么被折叠?



