溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

boost thread 類應(yīng)用以及資源耗盡異常

發(fā)布時間:2020-07-20 10:41:59 來源:網(wǎng)絡(luò) 閱讀:1066 作者:fengyuzaitu 欄目:系統(tǒng)運(yùn)維

1測試?yán)?/p>

#include <iostream>

#include <string>

#include <boost/thread/thread.hpp>


void ThreadFunc()

{

std::cout << "Welcome to thread function" << std::endl;

}

int main(int argc, char* argv[])

{

boost::thread instance(&ThreadFunc);

instance.join();

return 0;

}


2 攜帶參數(shù)例子

#include <boost/thread/thread.hpp>

#include <boost/bind.hpp>

#include <iostream>


void threadFunc(const char* pszContext)

{

std::cout << pszContext << std::endl;

}


int main(int argc, char* argv[])

{

char* pszContext = "fengyuzaitu@126.com";

boost::thread thread1(boost::bind(&threadFunc, pszContext));

thread1.join();

return 0;

}


3 類的非靜態(tài)函數(shù)作為線程函數(shù)

生產(chǎn)環(huán)境中經(jīng)常需要訪問類的私有成員,如果類的靜態(tài)函數(shù)作為線程函數(shù),通過參數(shù)的方式傳遞極其不方便

#include <iostream>

#include <string>

#include <boost/thread/thread.hpp>

#include <boost/function/function0.hpp>


class CThreadClass

{

public:


CThreadClass()

{

memset(m_szContext, 0x00, 1024);

}


void ThreadFunc()

{

std::cout << m_szContext << std::endl;

}


void StartThread()

{

strcpy_s(m_szContext, "Welcome to thread func\n");

boost::function0<void> f = boost::bind(&CThreadClass::ThreadFunc, this);

boost::thread thrd(f);

thrd.join();

}


private:


char m_szContext[1024];

};

int main(int argc, char* argv[])

{

CThreadClass instance;

instance.StartThread();

return 0;

}


4 創(chuàng)建線程過多,導(dǎo)致boost庫異常拋出,耗盡資源

查看boost::system::system_error = {m_error_code={m_val=11 m_cat=0x02d848f4 {CMMS-test.exe!boost::system::`anonymous-namespace'::generic_error_category generic_category_const} {...} } ...}

boost::throw_exception<boost::thread_resource_error>(const boost::thread_resource_error & e) 行 69?C++

boost::thread::start_thread() 行 180?C++

目前通過代碼測試生成1274個線程,實(shí)際上這是需要根據(jù)線程函數(shù)的實(shí)質(zhì)內(nèi)容決定的,在編碼中必須指定上限,否則會引起程序異常崩潰


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI