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
最新推荐文章于 2023-08-06 00:24:46 发布