欢迎光临
我们一直在努力

boost thread 类应用以及资源耗尽异常

1测试例子

#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 携带参数例子

#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 类的非静态函数作为线程函数

生产环境中经常需要访问类的私有成员,如果类的静态函数作为线程函数,通过参数的方式传递极其不方便

#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 创建线程过多,导致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个线程,实际上这是需要根据线程函数的实质内容决定的,在编码中必须指定上限,否则会引起程序异常崩溃

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。