接下來,聊一聊主題–Thread
/***Thread.h***/class Thread : boost::noncopyable //禁止拷貝{ public: typedef boost::function<void ()> ThreadFunc;//仿函數(shù)對(duì)象,利用回調(diào)的方式使用線程函數(shù) explicit Thread(const ThreadFunc&, const string& name = string());//普通的線程構(gòu)造函數(shù)#ifdef __GXX_EXPERIMENTAL_CXX0X__ explicit Thread(ThreadFunc&&, const string& name = string());//移動(dòng)的線程構(gòu)造函數(shù),比上面的更節(jié)省資源std::move#endif ~Thread();//析構(gòu)函數(shù) void start();//啟動(dòng)線程 int join(); // 類似于 pthread_join() bool started() const { return started_; } // pthread_t pthreadId() const { return pthreadId_; } pid_t tid() const { return *tid_; } //返回線程索引 const string& name() const { return name_; }//返回線程名字 static int numCreated() { return numCreated_.get(); } PRivate: void setDefaultName(); bool started_; //是否啟動(dòng) bool joined_; //是否終止 pthread_t pthreadId_; //線程索引 boost::shared_ptr<pid_t> tid_; //指向線程索引的智能指針 ThreadFunc func_; //線程主題函數(shù) string name_; //線程名字 static AtomicInt32 numCreated_; //static變量在所有的線程對(duì)象中共享,為由該類產(chǎn)生的線程排序};在muduo的線程對(duì)象封裝中,最精彩的是使用boost::function函數(shù)對(duì)象將線程函數(shù)以回調(diào)的方式傳遞進(jìn)線程對(duì)象中。typedef boost::function<void ()> ThreadFun;
將線程中的若干數(shù)據(jù)保存到ThreadData中,然后將ThreadData作為傳遞給pthread_create(...,void* arg)中的最后一個(gè)數(shù)據(jù)參數(shù)傳遞給void Thread(void* )標(biāo)準(zhǔn)的線程啟動(dòng)函數(shù)。然后在標(biāo)準(zhǔn)的線程啟動(dòng)函數(shù)內(nèi)將void* arg強(qiáng)行轉(zhuǎn)化為ThreadData,然后使用ThreadData中的runInThread函數(shù)啟動(dòng)線程。
在使用muduo的線程接口時(shí),使用bind將線程運(yùn)行函數(shù)再打包,然后傳遞進(jìn)Thread.
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注