muduo之ThreadLocal
生活随笔
收集整理的這篇文章主要介紹了
muduo之ThreadLocal
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
? ? ? ? ?ThreadLocal用來存儲線程私有數(shù)據(jù)的類。
// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_THREADLOCAL_H #define MUDUO_BASE_THREADLOCAL_H#include "muduo/base/Mutex.h" #include "muduo/base/noncopyable.h"#include <pthread.h>namespace muduo {template<typename T> class ThreadLocal : noncopyable //線程特定數(shù)據(jù) {public:ThreadLocal(){MCHECK(pthread_key_create(&pkey_, &ThreadLocal::destructor));//構(gòu)造函數(shù)中創(chuàng)建key,數(shù)據(jù)的銷毀由destructor來銷毀}~ThreadLocal(){MCHECK(pthread_key_delete(pkey_));//析構(gòu)函數(shù)中銷毀key}T& value()//獲取線程特定數(shù)據(jù){T* perThreadValue = static_cast<T*>(pthread_getspecific(pkey_));//通過key獲取線程特定數(shù)據(jù)if (!perThreadValue)//如果是空的,說明特定數(shù)據(jù)還沒有創(chuàng)建,那么就空構(gòu)造一個{T* newObj = new T();MCHECK(pthread_setspecific(pkey_, newObj));//設(shè)置特定數(shù)據(jù)perThreadValue = newObj;//返回}return *perThreadValue;//返回對象引用,所以需要*}private:static void destructor(void *x){T* obj = static_cast<T*>(x);typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];//檢測是否是完全類型T_must_be_complete_type dummy; (void) dummy;delete obj;//如果是,我們就可以刪除它了}private:pthread_key_t pkey_;//key的類型是pthread_key_t類型 };} // namespace muduo#endif // MUDUO_BASE_THREADLOCAL_H?
總結(jié)
以上是生活随笔為你收集整理的muduo之ThreadLocal的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: muduo之mutex和conditio
- 下一篇: muduo之Thread