本篇文章給大家分享的是有關(guān)Boost線程中類內(nèi)線程函數(shù)的示例分析,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
公司主營業(yè)務(wù):做網(wǎng)站、網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)公司是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)公司推出同安免費(fèi)做網(wǎng)站回饋大家。
代碼
#include <string>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/function/function0.hpp>
class CThreadClass
{
public:
CThreadClass()
{
m_stop = true;
}
void StartThread()
{
boost::function0<void> f = boost::bind(&CThreadClass::ThreadFunc, this);
boost::thread thrd(f);
}
void ThreadFunc()
{
std::cout << m_stop << std::endl;
}
private:
bool m_stop;
};
void ThreadTest()
{
CThreadClass helper;
helper.StartThread();
}
int main()
{
ThreadTest();
::Sleep(1000);
return 0;
}
在上面的例子中,在類的構(gòu)造函數(shù)中,初始化m_stop為true,但是在線程函數(shù)中訪問的時(shí)候,m_stop卻是為false,并且根據(jù)引用,
只有構(gòu)造函數(shù)對(duì)m_stop進(jìn)行了初始化操作
原因
ThreadTest函數(shù)實(shí)例化CThreadClass,創(chuàng)建線程,當(dāng)ThreadTest調(diào)用結(jié)束的時(shí)候,helper實(shí)例就會(huì)由于生命周期結(jié)束,
而在棧中被銷毀,這個(gè)時(shí)候,m_stop的值就是未知的,有的時(shí)候如果寄存器中的值沒有被清空,或者置位,程序正常運(yùn)行
上述代碼來自于項(xiàng)目中的不成熟的使用方案,通過該方法來創(chuàng)建一個(gè)監(jiān)聽服務(wù),切記!!
優(yōu)雅
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/function/function0.hpp>
class CThreadClass
{
public:
CThreadClass()
{
m_stop = false;
}
void StartThread()
{
m_thread.reset(new boost::thread(boost::bind(&CThreadClass::ThreadFunc, this)));
}
void StopThread()
{
m_stop = true;
m_thread->join();
}
void ThreadFunc()
{
while (!m_stop)
{
std::cout << "thread is running" << std::endl;
::Sleep(100);
}
}
private:
bool m_stop;
boost::shared_ptr<boost::thread> m_thread;
};
CThreadClass* pHelper = NULL;
void StartListen()
{
pHelper = new CThreadClass();
pHelper->StartThread();
}
void StopListen()
{
if (NULL == pHelper) return;
delete pHelper;
pHelper = NULL;
}
int main()
{
StartListen();
::Sleep(1000);
StopListen();
return 0;
}
注意:reset前面是.,而join前面是->,目前沒有明白
以上就是Boost線程中類內(nèi)線程函數(shù)的示例分析,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享文章:Boost線程中類內(nèi)線程函數(shù)的示例分析
分享URL:http://chinadenli.net/article44/gojgee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、外貿(mào)建站、企業(yè)網(wǎng)站制作、App設(shè)計(jì)、網(wǎng)站設(shè)計(jì)公司、網(wǎng)站設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)